コード例 #1
0
        /// <summary>
        /// Get a new Nonce. Required for the majority of api requests.
        /// </summary>
        /// <param name="directory">Directory object.</param>
        /// <returns>Nonce string. Wrapped by a response object.</returns>
        public async Task <AcmeApiResponse> GetNonceAsync(AcmeDirectory directory)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (string.IsNullOrEmpty(directory.NewNoonce))
            {
                throw new ArgumentException("directory is missing NewNonce url.");
            }

            HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Head, directory.NewNoonce);
            var apiResp            = await _httpClient.SendAsync(msg);

            if (!apiResp.IsSuccessStatusCode)
            {
                return(ErrorResponse(await apiResp.Content?.ReadAsStringAsync()));
            }

            if (!apiResp.Headers.TryGetValues(ProtoacmeContants.HEADER_NONCE, out IEnumerable <string> values))
            {
                return(ErrorResponse("Call to get new nonce missing NONCE header."));
            }

            return(new AcmeApiResponse()
            {
                Status = AcmeApiResponseStatus.Success,
                Nonce = values.FirstOrDefault()
            });
        }
コード例 #2
0
        /// <summary>
        /// Updates an existing accounts contacts
        /// </summary>
        /// <param name="directory">Directory object.</param>
        /// <param name="nonce">Nonce</param>
        /// <param name="account">Must be existing account.</param>
        /// <returns>Return api response with status.</returns>
        public async Task <AcmeApiResponse> UpdateAccountAsync(AcmeDirectory directory, string nonce, AcmeAccount account)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (string.IsNullOrEmpty(directory.NewAccount))
            {
                throw new ArgumentException("directory is missing Account url.");
            }
            if (string.IsNullOrEmpty(nonce))
            {
                throw new ArgumentNullException("nonce");
            }
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            AcmeCreateAccount upd = new AcmeCreateAccount()
            {
                Contact = account.Contact, TermsOfServiceAgreed = true
            };

            JwsContainer <AcmeCreateAccount> jwsObject = new JwsContainer <AcmeCreateAccount>(account.SecurityInfo, nonce, account.KID, account.KID, upd);

            string jwsToken = jwsObject.SerializeSignedToken();

            var apiResp = await SendPostData(
                url : _letsEncryptEndpoint.AppendUrl(ProtoacmeContants.LETSENCRYPT_ACCOUNT_FRAGMENT).AppendUrl(account.Id.ToString()),
                data : jwsToken);

            string apiRespString = await apiResp.Content?.ReadAsStringAsync();

            if (apiResp.StatusCode != HttpStatusCode.OK)
            {
                return(ErrorResponse(apiRespString));
            }

            if (!apiResp.Headers.TryGetValues(ProtoacmeContants.HEADER_NONCE, out IEnumerable <string> nonces))
            {
                return(ErrorResponse <AcmeAccount>("Missing Replay-Nonce Header on CreateAccount (UPDATE) Response."));
            }

            return(new AcmeApiResponse()
            {
                Status = AcmeApiResponseStatus.Success,
                Nonce = nonces.FirstOrDefault()
            });
        }
コード例 #3
0
ファイル: AcmeTests.cs プロジェクト: orf53975/IoTGateway
        public async Task ACME_Test_01_GetDirectory()
        {
            AcmeDirectory Directory = await this.client.GetDirectory();

            Assert.IsNotNull(Directory);
            Assert.IsTrue(Directory.CaaIdentities.Length > 0);
            Assert.IsFalse(Directory.ExternalAccountRequired);
            Assert.IsNotNull(Directory.KeyChange);
            Assert.IsNotNull(Directory.NewAccount);
            Assert.IsNull(Directory.NewAuthz);
            Assert.IsNotNull(Directory.NewNonce);
            Assert.IsNotNull(Directory.NewOrder);
            Assert.IsNotNull(Directory.RevokeCert);
            Assert.IsNotNull(Directory.TermsOfService);
            Assert.IsNotNull(Directory.Website);
        }
コード例 #4
0
        internal async Task <bool> CreateCertificate(string TabID)
        {
            try
            {
                string        URL = this.customCA ? this.acmeDirectory : "https://acme-v02.api.letsencrypt.org/directory";
                RSAParameters Parameters;
                CspParameters CspParams = new CspParameters()
                {
                    Flags            = CspProviderFlags.UseMachineKeyStore,
                    KeyContainerName = "IoTGateway:" + URL
                };

                try
                {
                    bool Ok;

                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096, CspParams))
                    {
                        Parameters = RSA.ExportParameters(true);

                        if (RSA.KeySize < 4096)
                        {
                            RSA.PersistKeyInCsp = false;
                            RSA.Clear();
                            Ok = false;
                        }
                        else
                        {
                            Ok = true;
                        }
                    }

                    if (!Ok)
                    {
                        using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096, CspParams))
                        {
                            Parameters = RSA.ExportParameters(true);
                        }
                    }
                }
                catch (CryptographicException ex)
                {
                    throw new CryptographicException("Unable to get access to cryptographic key for \"IoTGateway:" + URL +
                                                     "\". Was the database created using another user?", ex);
                }

                using (AcmeClient Client = new AcmeClient(new Uri(URL), Parameters))
                {
                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Connecting to directory.", false, "User");

                    AcmeDirectory AcmeDirectory = await Client.GetDirectory();

                    if (AcmeDirectory.ExternalAccountRequired)
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "An external account is required.", false, "User");
                    }

                    if (AcmeDirectory.TermsOfService != null)
                    {
                        URL = AcmeDirectory.TermsOfService.ToString();
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Terms of service available on: " + URL, false, "User");
                        ClientEvents.PushEvent(new string[] { TabID }, "TermsOfService", URL, false, "User");

                        this.urlToS = URL;

                        if (!this.acceptToS)
                        {
                            ClientEvents.PushEvent(new string[] { TabID }, "CertificateError", "You need to accept the terms of service.", false, "User");
                            return(false);
                        }
                    }

                    if (AcmeDirectory.Website != null)
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Web site available on: " + AcmeDirectory.Website.ToString(), false, "User");
                    }

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Getting account.", false, "User");

                    List <string> Names = new List <string>();

                    if (!string.IsNullOrEmpty(this.domain))
                    {
                        Names.Add(this.domain);
                    }

                    if (this.alternativeDomains != null)
                    {
                        foreach (string Name in this.alternativeDomains)
                        {
                            if (!Names.Contains(Name))
                            {
                                Names.Add(Name);
                            }
                        }
                    }
                    string[] DomainNames = Names.ToArray();

                    AcmeAccount Account;

                    try
                    {
                        Account = await Client.GetAccount();

                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Account found.", false, "User");
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Created: " + Account.CreatedAt.ToString(), false, "User");
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Initial IP: " + Account.InitialIp, false, "User");
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Status: " + Account.Status.ToString(), false, "User");

                        if (string.IsNullOrEmpty(this.contactEMail))
                        {
                            if (Account.Contact != null && Account.Contact.Length != 0)
                            {
                                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Updating contact URIs in account.", false, "User");
                                Account = await Account.Update(new string[0]);

                                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Account updated.", false, "User");
                            }
                        }
                        else
                        {
                            if (Account.Contact is null || Account.Contact.Length != 1 || Account.Contact[0] != "mailto:" + this.contactEMail)
                            {
                                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Updating contact URIs in account.", false, "User");
                                Account = await Account.Update(new string[] { "mailto:" + this.contactEMail });

                                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Account updated.", false, "User");
                            }
                        }
                    }
                    catch (AcmeAccountDoesNotExistException)
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Account not found.", false, "User");
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Creating account.", false, "User");

                        Account = await Client.CreateAccount(string.IsNullOrEmpty(this.contactEMail)?new string[0] : new string[] { "mailto:" + this.contactEMail },
                                                             this.acceptToS);

                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Account created.", false, "User");
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Status: " + Account.Status.ToString(), false, "User");
                    }

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Generating new key.", false, "User");
                    await Account.NewKey();

                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096, CspParams))
                    {
                        RSA.ImportParameters(Client.ExportAccountKey(true));
                    }

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "New key generated.", false, "User");

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Creating order.", false, "User");
                    AcmeOrder Order = await Account.OrderCertificate(DomainNames, null, null);

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Order created.", false, "User");

                    foreach (AcmeAuthorization Authorization in await Order.GetAuthorizations())
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Processing authorization for " + Authorization.Value, false, "User");

                        AcmeChallenge Challenge;
                        bool          Acknowledged = false;
                        int           Index        = 1;
                        int           NrChallenges = Authorization.Challenges.Length;

                        for (Index = 1; Index <= NrChallenges; Index++)
                        {
                            Challenge = Authorization.Challenges[Index - 1];

                            if (Challenge is AcmeHttpChallenge HttpChallenge)
                            {
                                this.challenge = "/" + HttpChallenge.Token;
                                this.token     = HttpChallenge.KeyAuthorization;

                                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Acknowleding challenge.", false, "User");
                                Challenge = await HttpChallenge.AcknowledgeChallenge();

                                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Challenge acknowledged: " + Challenge.Status.ToString(), false, "User");

                                Acknowledged = true;
                            }
                        }

                        if (!Acknowledged)
                        {
                            ClientEvents.PushEvent(new string[] { TabID }, "CertificateError", "No automated method found to respond to any of the authorization challenges.", false, "User");
                            return(false);
                        }

                        AcmeAuthorization Authorization2 = Authorization;

                        do
                        {
                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Waiting to poll authorization status.", false, "User");
                            await Task.Delay(5000);

                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Polling authorization.", false, "User");
                            Authorization2 = await Authorization2.Poll();

                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Authorization polled: " + Authorization2.Status.ToString(), false, "User");
                        }while (Authorization2.Status == AcmeAuthorizationStatus.pending);

                        if (Authorization2.Status != AcmeAuthorizationStatus.valid)
                        {
                            switch (Authorization2.Status)
                            {
                            case AcmeAuthorizationStatus.deactivated:
                                throw new Exception("Authorization deactivated.");

                            case AcmeAuthorizationStatus.expired:
                                throw new Exception("Authorization expired.");

                            case AcmeAuthorizationStatus.invalid:
                                throw new Exception("Authorization invalid.");

                            case AcmeAuthorizationStatus.revoked:
                                throw new Exception("Authorization revoked.");

                            default:
                                throw new Exception("Authorization not validated.");
                            }
                        }
                    }

                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096))                       // TODO: Make configurable
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Finalizing order.", false, "User");

                        SignatureAlgorithm SignAlg = new RsaSha256(RSA);

                        Order = await Order.FinalizeOrder(new CertificateRequest(SignAlg)
                        {
                            CommonName = this.domain,
                            SubjectAlternativeNames = DomainNames,
                            EMailAddress            = this.contactEMail
                        });

                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Order finalized: " + Order.Status.ToString(), false, "User");

                        if (Order.Status != AcmeOrderStatus.valid)
                        {
                            switch (Order.Status)
                            {
                            case AcmeOrderStatus.invalid:
                                throw new Exception("Order invalid.");

                            default:
                                throw new Exception("Unable to validate oder.");
                            }
                        }

                        if (Order.Certificate is null)
                        {
                            throw new Exception("No certificate URI provided.");
                        }

                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Downloading certificate.", false, "User");

                        X509Certificate2[] Certificates = await Order.DownloadCertificate();

                        X509Certificate2 Certificate = Certificates[0];

                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Exporting certificate.", false, "User");

                        this.certificate = Certificate.Export(X509ContentType.Cert);
                        this.privateKey  = RSA.ExportCspBlob(true);
                        this.pfx         = null;
                        this.password    = string.Empty;

                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Adding private key.", false, "User");

                        try
                        {
                            Certificate.PrivateKey = RSA;
                        }
                        catch (PlatformNotSupportedException)
                        {
                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Platform does not support adding of private key.", false, "User");
                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Searching for OpenSSL on machine.", false, "User");

                            string[] Files;
                            string   Password      = Hashes.BinaryToString(Gateway.NextBytes(32));
                            string   CertFileName  = null;
                            string   CertFileName2 = null;
                            string   KeyFileName   = null;

                            if (string.IsNullOrEmpty(this.openSslPath) || !File.Exists(this.openSslPath))
                            {
                                Files = GetFiles(new string(Path.DirectorySeparatorChar, 1), "openssl.exe");
                                if (Files is null)
                                {
                                    List <string> Files2 = new List <string>();

                                    Files = GetFiles(Environment.SpecialFolder.ProgramFiles, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.CommonProgramFilesX86, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.Programs, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.System, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.SystemX86, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.Windows, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.CommonProgramFiles, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.CommonProgramFilesX86, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Environment.SpecialFolder.CommonPrograms, "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Path.DirectorySeparatorChar + "OpenSSL-Win32", "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = GetFiles(Path.DirectorySeparatorChar + "OpenSSL-Win64", "openssl.exe");
                                    if (Files != null)
                                    {
                                        Files2.AddRange(Files);
                                    }

                                    Files = Files2.ToArray();
                                }
                            }
                            else
                            {
                                Files = new string[] { this.openSslPath }
                            };

                            try
                            {
                                if (Files.Length == 0)
                                {
                                    ClientEvents.PushEvent(new string[] { TabID }, "CertificateError", "Unable to join certificate with private key. Try installing <a target=\"_blank\" href=\"https://wiki.openssl.org/index.php/Binaries\">OpenSSL</a> and try again.", false, "User");
                                    return(false);
                                }
                                else
                                {
                                    foreach (string OpenSslFile in Files)
                                    {
                                        if (CertFileName is null)
                                        {
                                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Generating temporary certificate file.", false, "User");

                                            StringBuilder PemOutput = new StringBuilder();
                                            byte[]        Bin       = Certificate.Export(X509ContentType.Cert);

                                            PemOutput.AppendLine("-----BEGIN CERTIFICATE-----");
                                            PemOutput.AppendLine(Convert.ToBase64String(Bin, Base64FormattingOptions.InsertLineBreaks));
                                            PemOutput.AppendLine("-----END CERTIFICATE-----");

                                            CertFileName = Path.Combine(Gateway.AppDataFolder, "Certificate.pem");
                                            File.WriteAllText(CertFileName, PemOutput.ToString(), Encoding.ASCII);

                                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Generating temporary key file.", false, "User");

                                            DerEncoder KeyOutput = new DerEncoder();
                                            SignAlg.ExportPrivateKey(KeyOutput);

                                            PemOutput.Clear();
                                            PemOutput.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
                                            PemOutput.AppendLine(Convert.ToBase64String(KeyOutput.ToArray(), Base64FormattingOptions.InsertLineBreaks));
                                            PemOutput.AppendLine("-----END RSA PRIVATE KEY-----");

                                            KeyFileName = Path.Combine(Gateway.AppDataFolder, "Certificate.key");

                                            File.WriteAllText(KeyFileName, PemOutput.ToString(), Encoding.ASCII);
                                        }

                                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Converting to PFX using " + OpenSslFile, false, "User");

                                        Process P = new Process()
                                        {
                                            StartInfo = new ProcessStartInfo()
                                            {
                                                FileName               = OpenSslFile,
                                                Arguments              = "pkcs12 -nodes -export -out Certificate.pfx -inkey Certificate.key -in Certificate.pem -password pass:"******"ShowStatus", "Output: " + P.StandardOutput.ReadToEnd(), false, "User");
                                            }

                                            if (!P.StandardError.EndOfStream)
                                            {
                                                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Error: " + P.StandardError.ReadToEnd(), false, "User");
                                            }

                                            continue;
                                        }

                                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Loading PFX.", false, "User");

                                        CertFileName2    = Path.Combine(Gateway.AppDataFolder, "Certificate.pfx");
                                        this.pfx         = File.ReadAllBytes(CertFileName2);
                                        this.password    = Password;
                                        this.openSslPath = OpenSslFile;

                                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "PFX successfully generated using OpenSSL.", false, "User");
                                        break;
                                    }

                                    if (this.pfx is null)
                                    {
                                        this.openSslPath = string.Empty;
                                        ClientEvents.PushEvent(new string[] { TabID }, "CertificateError", "Unable to convert to PFX using OpenSSL.", false, "User");
                                        return(false);
                                    }
                                }
                            }
                            finally
                            {
                                if (CertFileName != null && File.Exists(CertFileName))
                                {
                                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Deleting temporary certificate file.", false, "User");
                                    File.Delete(CertFileName);
                                }

                                if (KeyFileName != null && File.Exists(KeyFileName))
                                {
                                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Deleting temporary key file.", false, "User");
                                    File.Delete(KeyFileName);
                                }

                                if (CertFileName2 != null && File.Exists(CertFileName2))
                                {
                                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Deleting temporary pfx file.", false, "User");
                                    File.Delete(CertFileName2);
                                }
                            }
                        }


                        if (this.Step < 2)
                        {
                            this.Step = 2;
                        }

                        this.Updated = DateTime.Now;
                        await Database.Update(this);

                        ClientEvents.PushEvent(new string[] { TabID }, "CertificateOk", string.Empty, false, "User");

                        Gateway.UpdateCertificate(this);

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
                ClientEvents.PushEvent(new string[] { TabID }, "CertificateError", "Unable to create certificate: " + XML.HtmlValueEncode(ex.Message), false, "User");
                return(false);
            }
            finally
            {
                this.inProgress = false;
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: ikvm/IoTGateway
        private static async Task Process(bool Verbose, Uri Directory, string[] ContactURLs, bool TermsOfServiceAgreed,
                                          bool NewKey, string[] DomainNames, DateTime?NotBefore, DateTime?NotAfter, string HttpRootFolder, int PollingInterval,
                                          int KeySize, string EMail, string Country, string Locality, string StateOrProvince, string Organization,
                                          string OrganizationalUnit, string FileName, string Password)
        {
            using (AcmeClient Client = new AcmeClient(Directory))
            {
                Log.Informational("Connecting to directory.",
                                  new KeyValuePair <string, object>("URL", Directory.ToString()));

                AcmeDirectory AcmeDirectory = await Client.GetDirectory();

                if (AcmeDirectory.ExternalAccountRequired)
                {
                    Log.Warning("An external account is required.");
                }

                if (AcmeDirectory.TermsOfService != null)
                {
                    Log.Informational("Terms of service available.",
                                      new KeyValuePair <string, object>("URL", AcmeDirectory.TermsOfService.ToString()));
                }

                if (AcmeDirectory.Website != null)
                {
                    Log.Informational("Web site available.",
                                      new KeyValuePair <string, object>("URL", AcmeDirectory.Website.ToString()));
                }


                Log.Informational("Getting account.");

                AcmeAccount Account;

                try
                {
                    Account = await Client.GetAccount();

                    Log.Informational("Account found.",
                                      new KeyValuePair <string, object>("Created", Account.CreatedAt),
                                      new KeyValuePair <string, object>("Initial IP", Account.InitialIp),
                                      new KeyValuePair <string, object>("Status", Account.Status),
                                      new KeyValuePair <string, object>("Contact", Account.Contact));

                    if (ContactURLs != null && !AreEqual(Account.Contact, ContactURLs))
                    {
                        Log.Informational("Updating contact URIs in account.");

                        Account = await Account.Update(ContactURLs);

                        Log.Informational("Account updated.",
                                          new KeyValuePair <string, object>("Created", Account.CreatedAt),
                                          new KeyValuePair <string, object>("Initial IP", Account.InitialIp),
                                          new KeyValuePair <string, object>("Status", Account.Status),
                                          new KeyValuePair <string, object>("Contact", Account.Contact));
                    }
                }
                catch (AcmeAccountDoesNotExistException)
                {
                    Log.Warning("Account not found. Creating account.",
                                new KeyValuePair <string, object>("Contact", ContactURLs),
                                new KeyValuePair <string, object>("TermsOfServiceAgreed", TermsOfServiceAgreed));

                    Account = await Client.CreateAccount(ContactURLs, TermsOfServiceAgreed);

                    Log.Informational("Account created.",
                                      new KeyValuePair <string, object>("Created", Account.CreatedAt),
                                      new KeyValuePair <string, object>("Initial IP", Account.InitialIp),
                                      new KeyValuePair <string, object>("Status", Account.Status),
                                      new KeyValuePair <string, object>("Contact", Account.Contact));
                }

                if (NewKey)
                {
                    Log.Informational("Generating new key.");

                    await Account.NewKey();

                    Log.Informational("New key generated.");
                }


                if (DomainNames != null)
                {
                    if (!string.IsNullOrEmpty(HttpRootFolder))
                    {
                        CheckExists(HttpRootFolder);
                        HttpRootFolder = Path.Combine(HttpRootFolder, ".well-known");
                        CheckExists(HttpRootFolder);
                        HttpRootFolder = Path.Combine(HttpRootFolder, "acme-challenge");
                        CheckExists(HttpRootFolder);
                    }

                    Log.Informational("Creating order.");

                    AcmeOrder Order = await Account.OrderCertificate(DomainNames, NotBefore, NotAfter);

                    Log.Informational("Order created.",
                                      new KeyValuePair <string, object>("Status", Order.Status),
                                      new KeyValuePair <string, object>("Expires", Order.Expires),
                                      new KeyValuePair <string, object>("NotBefore", Order.NotBefore),
                                      new KeyValuePair <string, object>("NotAfter", Order.NotAfter),
                                      new KeyValuePair <string, object>("Identifiers", Order.Identifiers));

                    List <string> FileNames = null;

                    try
                    {
                        foreach (AcmeAuthorization Authorization in await Order.GetAuthorizations())
                        {
                            Log.Informational("Processing authorization.",
                                              new KeyValuePair <string, object>("Type", Authorization.Type),
                                              new KeyValuePair <string, object>("Value", Authorization.Value),
                                              new KeyValuePair <string, object>("Status", Authorization.Status),
                                              new KeyValuePair <string, object>("Expires", Authorization.Expires),
                                              new KeyValuePair <string, object>("Wildcard", Authorization.Wildcard));

                            AcmeChallenge Challenge;
                            bool          Manual       = true;
                            int           Index        = 1;
                            int           NrChallenges = Authorization.Challenges.Length;
                            string        s;

                            for (Index = 1; Index <= NrChallenges; Index++)
                            {
                                Challenge = Authorization.Challenges[Index - 1];

                                if (Challenge is AcmeHttpChallenge HttpChallenge)
                                {
                                    Log.Informational(Index.ToString() + ") HTTP challenge.",
                                                      new KeyValuePair <string, object>("Resource", HttpChallenge.ResourceName),
                                                      new KeyValuePair <string, object>("Response", HttpChallenge.KeyAuthorization),
                                                      new KeyValuePair <string, object>("Content-Type", "application/octet-stream"));

                                    if (!string.IsNullOrEmpty(HttpRootFolder))
                                    {
                                        string ChallengeFileName = Path.Combine(HttpRootFolder, HttpChallenge.Token);
                                        File.WriteAllBytes(ChallengeFileName, Encoding.ASCII.GetBytes(HttpChallenge.KeyAuthorization));

                                        if (FileNames == null)
                                        {
                                            FileNames = new List <string>();
                                        }

                                        FileNames.Add(ChallengeFileName);

                                        Log.Informational("Acknowleding challenge.");

                                        Challenge = await HttpChallenge.AcknowledgeChallenge();

                                        Log.Informational("Challenge acknowledged.",
                                                          new KeyValuePair <string, object>("Status", Challenge.Status));

                                        Manual = false;
                                    }
                                    else if (!Verbose)
                                    {
                                        Console.Out.WriteLine(Index.ToString() + ") HTTP challenge.");
                                        Console.Out.WriteLine("Resource: " + HttpChallenge.ResourceName);
                                        Console.Out.WriteLine("Response: " + HttpChallenge.KeyAuthorization);
                                        Console.Out.WriteLine("Content-Type: " + "application/octet-stream");
                                    }
                                }
                                else if (Challenge is AcmeDnsChallenge DnsChallenge)
                                {
                                    Log.Informational(Index.ToString() + ") DNS challenge.",
                                                      new KeyValuePair <string, object>("Domain", DnsChallenge.ValidationDomainNamePrefix + Authorization.Value),
                                                      new KeyValuePair <string, object>("TXT Record", DnsChallenge.KeyAuthorization));

                                    if (!Verbose)
                                    {
                                        Console.Out.WriteLine(Index.ToString() + ") DNS challenge.");
                                        Console.Out.WriteLine("Domain: " + DnsChallenge.ValidationDomainNamePrefix + Authorization.Value);
                                        Console.Out.WriteLine("TXT Record: " + DnsChallenge.KeyAuthorization);
                                    }
                                }
                            }

                            if (Manual)
                            {
                                Console.Out.WriteLine();
                                Console.Out.WriteLine("No automated method found to respond to any of the authorization challenges. " +
                                                      "You can respond to a challenge manually. After configuring the corresponding " +
                                                      "resource, enter the number of the corresponding challenge and press ENTER to acknowledge it.");

                                do
                                {
                                    Console.Out.Write("Challenge to acknowledge: ");
                                    s = Console.In.ReadLine();
                                }while (!int.TryParse(s, out Index) || Index <= 0 || Index > NrChallenges);

                                Log.Informational("Acknowleding challenge.");

                                Challenge = await Authorization.Challenges[Index - 1].AcknowledgeChallenge();

                                Log.Informational("Challenge acknowledged.",
                                                  new KeyValuePair <string, object>("Status", Challenge.Status));
                            }

                            AcmeAuthorization Authorization2 = Authorization;

                            do
                            {
                                Log.Informational("Waiting to poll authorization status.",
                                                  new KeyValuePair <string, object>("ms", PollingInterval));

                                System.Threading.Thread.Sleep(PollingInterval);

                                Log.Informational("Polling authorization.");

                                Authorization2 = await Authorization2.Poll();

                                Log.Informational("Authorization polled.",
                                                  new KeyValuePair <string, object>("Type", Authorization2.Type),
                                                  new KeyValuePair <string, object>("Value", Authorization2.Value),
                                                  new KeyValuePair <string, object>("Status", Authorization2.Status),
                                                  new KeyValuePair <string, object>("Expires", Authorization2.Expires),
                                                  new KeyValuePair <string, object>("Wildcard", Authorization2.Wildcard));
                            }while (Authorization2.Status == AcmeAuthorizationStatus.pending);

                            if (Authorization2.Status != AcmeAuthorizationStatus.valid)
                            {
                                switch (Authorization2.Status)
                                {
                                case AcmeAuthorizationStatus.deactivated:
                                    throw new Exception("Authorization deactivated.");

                                case AcmeAuthorizationStatus.expired:
                                    throw new Exception("Authorization expired.");

                                case AcmeAuthorizationStatus.invalid:
                                    throw new Exception("Authorization invalid.");

                                case AcmeAuthorizationStatus.revoked:
                                    throw new Exception("Authorization revoked.");

                                default:
                                    throw new Exception("Authorization not validated.");
                                }
                            }
                        }

                        using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(KeySize))
                        {
                            Log.Informational("Finalizing order.");

                            SignatureAlgorithm SignAlg = new RsaSha256(RSA);

                            Order = await Order.FinalizeOrder(new Security.ACME.CertificateRequest(SignAlg)
                            {
                                CommonName = DomainNames[0],
                                SubjectAlternativeNames = DomainNames,
                                EMailAddress            = EMail,
                                Country            = Country,
                                Locality           = Locality,
                                StateOrProvince    = StateOrProvince,
                                Organization       = Organization,
                                OrganizationalUnit = OrganizationalUnit
                            });

                            Log.Informational("Order finalized.",
                                              new KeyValuePair <string, object>("Status", Order.Status),
                                              new KeyValuePair <string, object>("Expires", Order.Expires),
                                              new KeyValuePair <string, object>("NotBefore", Order.NotBefore),
                                              new KeyValuePair <string, object>("NotAfter", Order.NotAfter),
                                              new KeyValuePair <string, object>("Identifiers", Order.Identifiers));

                            if (Order.Status != AcmeOrderStatus.valid)
                            {
                                switch (Order.Status)
                                {
                                case AcmeOrderStatus.invalid:
                                    throw new Exception("Order invalid.");

                                default:
                                    throw new Exception("Unable to validate oder.");
                                }
                            }

                            if (Order.Certificate == null)
                            {
                                throw new Exception("No certificate URI provided.");
                            }

                            System.Security.Cryptography.X509Certificates.X509Certificate2[] Certificates =
                                await Order.DownloadCertificate();

                            string CertificateFileName;
                            string CertificateFileName2;
                            int    Index = 1;
                            byte[] Bin;

                            DerEncoder KeyOutput = new DerEncoder();
                            SignAlg.ExportPrivateKey(KeyOutput);

                            StringBuilder PemOutput = new StringBuilder();

                            PemOutput.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
                            PemOutput.AppendLine(Convert.ToBase64String(KeyOutput.ToArray(), Base64FormattingOptions.InsertLineBreaks));
                            PemOutput.AppendLine("-----END RSA PRIVATE KEY-----");

                            CertificateFileName = FileName + ".key";

                            Log.Informational("Saving private key.",
                                              new KeyValuePair <string, object>("FileName", CertificateFileName));

                            File.WriteAllText(CertificateFileName, PemOutput.ToString(), Encoding.ASCII);

                            foreach (X509Certificate2 Certificate in Certificates)
                            {
                                if (Index == 1)
                                {
                                    CertificateFileName = FileName;
                                }
                                else
                                {
                                    CertificateFileName = FileName + Index.ToString();
                                }

                                CertificateFileName2 = CertificateFileName + ".pem";
                                CertificateFileName += ".cer";

                                Bin = Certificate.Export(X509ContentType.Cert);

                                Log.Informational("Saving certificate.",
                                                  new KeyValuePair <string, object>("FileName", CertificateFileName),
                                                  new KeyValuePair <string, object>("FileName2", CertificateFileName2),
                                                  new KeyValuePair <string, object>("FriendlyName", Certificate.FriendlyName),
                                                  new KeyValuePair <string, object>("HasPrivateKey", Certificate.HasPrivateKey),
                                                  new KeyValuePair <string, object>("Issuer", Certificate.Issuer),
                                                  new KeyValuePair <string, object>("NotAfter", Certificate.NotAfter),
                                                  new KeyValuePair <string, object>("NotBefore", Certificate.NotBefore),
                                                  new KeyValuePair <string, object>("SerialNumber", Certificate.SerialNumber),
                                                  new KeyValuePair <string, object>("Subject", Certificate.Subject),
                                                  new KeyValuePair <string, object>("Thumbprint", Certificate.Thumbprint));

                                File.WriteAllBytes(CertificateFileName, Bin);

                                PemOutput.Clear();
                                PemOutput.AppendLine("-----BEGIN CERTIFICATE-----");
                                PemOutput.AppendLine(Convert.ToBase64String(Bin, Base64FormattingOptions.InsertLineBreaks));
                                PemOutput.AppendLine("-----END CERTIFICATE-----");

                                File.WriteAllText(CertificateFileName2, PemOutput.ToString(), Encoding.ASCII);

                                Index++;
                            }
                        }
                    }
                    finally
                    {
                        if (FileNames != null)
                        {
                            foreach (string FileName2 in FileNames)
                            {
                                File.Delete(FileName2);
                            }
                        }
                    }
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Sends a new order requesting a new certificate.
        /// </summary>
        /// <param name="directory">Directory object.</param>
        /// <param name="nonce">Nonce</param>
        /// <param name="account">Must be existing account.</param>
        /// <param name="certificates">Info describing the dns entries you are requesting certificates for.</param>
        /// <returns>A certificate fulfillment promise that is used to complete the certification chain in future requests.  Wrapped by a response object.</returns>
        public async Task <AcmeApiResponse <AcmeCertificateFulfillmentPromise> > RequestCertificateAsync(AcmeDirectory directory, string nonce, AcmeAccount account, AcmeCertificateRequest certificates)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (string.IsNullOrEmpty(directory.NewAccount))
            {
                throw new ArgumentException("directory is missing Account url.");
            }
            if (string.IsNullOrEmpty(nonce))
            {
                throw new ArgumentNullException("nonce");
            }
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }
            if (certificates == null)
            {
                throw new ArgumentNullException("certificates");
            }
            if (certificates.Identifiers == null || !certificates.Identifiers.Any())
            {
                throw new ArgumentException("Certificate is missing identifiers");
            }

            JwsContainer <AcmeCertificateRequest> jwsObject = new JwsContainer <AcmeCertificateRequest>(account.SecurityInfo, nonce, directory.NewOrder, account.KID, certificates);

            string jwsToken = jwsObject.SerializeSignedToken();

            var apiResp = await SendPostData(
                url : directory.NewOrder,
                data : jwsToken);

            string apiRespString = await apiResp.Content?.ReadAsStringAsync();

            if (apiResp.StatusCode != HttpStatusCode.Created)
            {
                return(ErrorResponse <AcmeCertificateFulfillmentPromise>(apiRespString));
            }

            if (!apiResp.Headers.TryGetValues(ProtoacmeContants.HEADER_NONCE, out IEnumerable <string> nonces))
            {
                return(ErrorResponse <AcmeCertificateFulfillmentPromise>("Missing Replay-Nonce Header on RequestCertificate Response."));
            }

            return(new AcmeApiResponse <AcmeCertificateFulfillmentPromise>()
            {
                Status = AcmeApiResponseStatus.Success,
                Nonce = nonces.FirstOrDefault(),
                Data = JsonConvert.DeserializeObject <AcmeCertificateFulfillmentPromise>(apiRespString)
            });
        }
コード例 #7
0
        /// <summary>
        /// Changes and updates the account security info for an existing account.
        /// </summary>
        /// <param name="directory">Directory object.</param>
        /// <param name="nonce">Nonce</param>
        /// <param name="account">Must be existing account.</param>
        /// <returns>Return api response with status.</returns>
        /// <remarks>Will update the security info on the passed in account, so you will need to reserialize and update your existing account object to update the security info.</remarks>
        public async Task <AcmeApiResponse> RollOverAccountKeyAsync(AcmeDirectory directory, string nonce, AcmeAccount account)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (string.IsNullOrEmpty(directory.NewAccount))
            {
                throw new ArgumentException("directory is missing Account url.");
            }
            if (string.IsNullOrEmpty(nonce))
            {
                throw new ArgumentNullException("nonce");
            }
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            RSACryptoServiceProvider cryptoProvider = new RSACryptoServiceProvider(2048);
            RSAParameters            rsaPrams       = cryptoProvider.ExportParameters(true);

            JwsContainer <ACCKEY> innerJwsObject = new JwsContainer <ACCKEY>(
                rsaPrams,
                nonce,
                directory.KeyChange,
                new ACCKEY()
            {
                account = account.KID,
                newKey  = new JWK()
                {
                    e   = Base64Tool.Encode(rsaPrams.Exponent),
                    kty = "RSA",
                    n   = Base64Tool.Encode(rsaPrams.Modulus)
                }
            });

            object signedInnerJwsObject = innerJwsObject.SerializeSignedObject();

            JwsContainer <object> outerJwsObject = new JwsContainer <object>(account.SecurityInfo, nonce, directory.KeyChange, account.KID, signedInnerJwsObject);

            string jwsToken = outerJwsObject.SerializeSignedToken();

            var apiResp = await SendPostData(
                url : directory.KeyChange,
                data : jwsToken);

            string apiRespString = await apiResp.Content?.ReadAsStringAsync();

            if (apiResp.StatusCode != HttpStatusCode.OK)
            {
                return(ErrorResponse(apiRespString));
            }

            if (!apiResp.Headers.TryGetValues(ProtoacmeContants.HEADER_NONCE, out IEnumerable <string> nonces))
            {
                return(ErrorResponse <AcmeAccount>("Missing Replay-Nonce Header on RolloverKey Response."));
            }

            account.SecurityInfo = rsaPrams;

            return(new AcmeApiResponse()
            {
                Status = AcmeApiResponseStatus.Success,
                Nonce = nonces.FirstOrDefault()
            });
        }
コード例 #8
0
        /// <summary>
        /// Creates a new account.
        /// </summary>
        /// <param name="directory">Directory object.</param>
        /// <param name="nonce">Nonce</param>
        /// <param name="account">Information for new account.</param>
        /// <returns>Returns a serializable account object. Wrapped by a response object.</returns>
        /// <remarks>It is best to serialize and save the account object so it can be retrieved later and used for renewing domains.</remarks>
        public async Task <AcmeApiResponse <AcmeAccount> > CreateAccountAsync(AcmeDirectory directory, string nonce, AcmeCreateAccount account)
        {
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (string.IsNullOrEmpty(directory.NewAccount))
            {
                throw new ArgumentException("directory is missing Account url.");
            }
            if (string.IsNullOrEmpty(nonce))
            {
                throw new ArgumentNullException("nonce");
            }
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            RSACryptoServiceProvider cryptoProvider = new RSACryptoServiceProvider(2048);
            RSAParameters            rsaPrams       = cryptoProvider.ExportParameters(true);

            JwsContainer <AcmeCreateAccount> jwsObject = new JwsContainer <AcmeCreateAccount>(rsaPrams, nonce, directory.NewAccount, account);

            string jwsToken = jwsObject.SerializeSignedToken();

            var apiResp = await SendPostData(
                url : directory.NewAccount,
                data : jwsToken);

            string apiRespString = await apiResp.Content?.ReadAsStringAsync();

            if (apiResp.StatusCode != HttpStatusCode.Created)
            {
                return(ErrorResponse <AcmeAccount>(apiRespString));
            }

            if (!apiResp.Headers.TryGetValues(ProtoacmeContants.HEADER_LOCATION, out IEnumerable <string> locations))
            {
                return(ErrorResponse <AcmeAccount>("Missing Location Header on CreateAccount Response."));
            }

            if (!apiResp.Headers.TryGetValues(ProtoacmeContants.HEADER_NONCE, out IEnumerable <string> nonces))
            {
                return(ErrorResponse <AcmeAccount>("Missing Replay-Nonce Header on CreateAccount Response."));
            }

            Dictionary <string, object> oResp = JsonConvert.DeserializeObject <Dictionary <string, object> >(apiRespString);

            var loc = locations.FirstOrDefault();
            var id  = int.Parse((new Uri(loc)).Segments.Last());

            return(new AcmeApiResponse <AcmeAccount>()
            {
                Status = AcmeApiResponseStatus.Success,
                Nonce = nonces.FirstOrDefault(),
                Data = new AcmeAccount()
                {
                    Id = id,
                    KID = loc,
                    SecurityInfo = rsaPrams,
                    Contact = account.Contact
                }
            });
        }