Пример #1
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (UseSystem)
                {
                    v.Proxy = null;
                }
                else
                {
                    v.Proxy = new Vault.ProxyConfig
                    {
                        UseNoProxy      = UseNoProxy,
                        ProxyURI        = UseProxy,
                        UseDefCred      = DefaultCredential,
                        Username        = Credential?.UserName,
                        PasswordEncoded = Credential?.GetNetworkCredential()?.Password,
                    };

                    if (!string.IsNullOrEmpty(v.Proxy.PasswordEncoded))
                    {
                        v.Proxy.PasswordEncoded = Convert.ToBase64String(Encoding.Unicode.GetBytes(
                                                                             v.Proxy.PasswordEncoded));
                    }
                };

                vp.SaveVault(v);
            }
        }
Пример #2
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.IssuerCertificates == null || v.IssuerCertificates.Count < 1)
                {
                    throw new InvalidOperationException("No issuer certificates found");
                }

                if (string.IsNullOrEmpty(SerialNumber))
                {
                    WriteObject(v.IssuerCertificates.Values, true);
                }
                else
                {
                    if (!v.IssuerCertificates.ContainsKey(SerialNumber))
                    {
                        throw new ItemNotFoundException("Unable to find an Issuer Certificate for the given serial number");
                    }

                    WriteObject(v.IssuerCertificates[SerialNumber]);
                }
            }
        }
Пример #3
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.ProviderConfigs == null || v.ProviderConfigs.Count < 1)
                {
                    throw new InvalidOperationException("No provider configs found");
                }

                if (List)
                {
                    foreach (var item in v.ProviderConfigs.Values)
                    {
                        WriteObject(item);
                    }
                }
                else
                {
                    var pc = v.ProviderConfigs.GetByRef(Ref);
                    if (pc == null)
                    {
                        throw new Exception("Unable to find Provider Config for the given reference");
                    }
                    var pcFilePath = Path.GetFullPath($"{pc.Id}.json");

                    WriteObject(pcFilePath);
                }
            }
        }
Пример #4
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Identifiers == null || v.Identifiers.Count < 1)
                {
                    throw new InvalidOperationException("No identifiers found");
                }

                var ii = v.Identifiers.GetByRef(Ref);
                if (ii == null)
                {
                    throw new Exception("Unable to find an Identifier for the given reference");
                }

                var authzState = ii.Authorization;

                if (!LocalOnly)
                {
                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        if (string.IsNullOrEmpty(Challenge))
                        {
                            authzState             = c.RefreshIdentifierAuthorization(authzState, UseBaseURI);
                            ii.AuthorizationUpdate = authzState;
                        }
                        else
                        {
                            c.RefreshAuthorizeChallenge(authzState, Challenge, UseBaseURI);
                            ii.Authorization = authzState;
                        }
                    }
                }

                v.Alias = StringHelper.IfNullOrEmpty(Alias);
                v.Label = StringHelper.IfNullOrEmpty(Label);
                v.Memo  = StringHelper.IfNullOrEmpty(Memo);

                vp.SaveVault(v);

                WriteObject(authzState);
            }
        }
Пример #5
0
        protected override void ProcessRecord()
        {
            var pc = new ProviderConfig
            {
                Id                = EntityHelper.NewId(),
                Alias             = Alias,
                Label             = Label,
                Memo              = Memo,
                DnsProvider       = DnsProvider,
                WebServerProvider = WebServerProvider,
            };

            var pcFilePath = Path.GetFullPath($"{pc.Id}.json");

            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.ProviderConfigs == null)
                {
                    v.ProviderConfigs = new EntityDictionary <ProviderConfig>();
                }
                v.ProviderConfigs.Add(pc);

                vp.SaveVault(v);
            }

            // TODO: this is *so* hardcoded, clean
            // up this provider resolution mechanism
            Stream s = null;

            if (!string.IsNullOrEmpty(DnsProvider))
            {
                s = typeof(ProviderConfig).Assembly.GetManifestResourceStream(
                    "LetsEncrypt.ACME.POSH.ProviderConfigSamples."
                    + $"dnsInfo.json.sample-{DnsProvider}DnsProvider");
            }
            if (!string.IsNullOrEmpty(WebServerProvider))
            {
                s = typeof(ProviderConfig).Assembly.GetManifestResourceStream(
                    "LetsEncrypt.ACME.POSH.ProviderConfigSamples."
                    + $"webServerInfo.json.sample-{WebServerProvider}WebServerProvider");
            }

            using (var fs = new FileStream(pcFilePath, FileMode.CreateNew))
            {
                s.CopyTo(fs);
            }
            s.Close();
            s.Dispose();

            WriteObject(pcFilePath);
        }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.IssuerCertificates == null || v.IssuerCertificates.Count < 1)
                {
                    throw new InvalidOperationException("No issuer certificates found");
                }

                if (string.IsNullOrEmpty(SerialNumber))
                {
                    WriteObject(v.IssuerCertificates.Values, true);
                }
                else
                {
                    if (!v.IssuerCertificates.ContainsKey(SerialNumber))
                    {
                        throw new ItemNotFoundException("Unable to find an Issuer Certificate for the given serial number");
                    }

                    var ic   = v.IssuerCertificates[SerialNumber];
                    var mode = Overwrite ? FileMode.Create : FileMode.CreateNew;

                    if (!string.IsNullOrEmpty(ExportCertificatePEM))
                    {
                        if (string.IsNullOrEmpty(ic.CrtPemFile))
                        {
                            throw new InvalidOperationException("Cannot export CRT; CRT hasn't been retrieved");
                        }
                        GetCertificate.CopyTo(vp, Vault.VaultAssetType.IssuerPem, ic.CrtPemFile,
                                              ExportCertificatePEM, mode);
                    }

                    if (!string.IsNullOrEmpty(ExportCertificateDER))
                    {
                        if (string.IsNullOrEmpty(ic.CrtDerFile))
                        {
                            throw new InvalidOperationException("Cannot export CRT; CRT hasn't been retrieved");
                        }

                        GetCertificate.CopyTo(vp, Vault.VaultAssetType.IssuerDer, ic.CrtDerFile,
                                              ExportCertificateDER, mode);
                    }

                    WriteObject(v.IssuerCertificates[SerialNumber]);
                }
            }
        }
Пример #7
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage(Force);
                var v = vp.LoadVault();

                v.Alias   = StringHelper.IfNullOrEmpty(Alias);
                v.Label   = StringHelper.IfNullOrEmpty(Label);
                v.Memo    = StringHelper.IfNullOrEmpty(Memo);
                v.BaseURI = StringHelper.IfNullOrEmpty(BaseURI);

                vp.SaveVault(v);
            }
        }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.ProviderConfigs == null || v.ProviderConfigs.Count < 1)
                {
                    throw new InvalidOperationException("No provider configs found");
                }

                if (List)
                {
                    foreach (var item in v.ProviderConfigs.Values)
                    {
                        WriteObject(item);
                    }
                }
                else
                {
                    var pc = v.ProviderConfigs.GetByRef(Ref);
                    if (pc == null)
                    {
                        throw new Exception("Unable to find Provider Config for the given reference");
                    }
                    var pcFilePath = Path.GetFullPath($"{pc.Id}.json");

                    // Copy out the asset to a temp file for editing
                    var pcAsset = vp.GetAsset(VaultAssetType.ProviderConfigInfo, $"{pc.Id}.json");
                    var temp    = Path.GetTempFileName();
                    using (var s = vp.LoadAsset(pcAsset))
                    {
                        using (var fs = new FileStream(temp, FileMode.Create))
                        {
                            s.CopyTo(fs);
                        }
                    }
                    NewProviderConfig.EditFile(temp, EditWith);

                    using (Stream fs = new FileStream(temp, FileMode.Open),
                           assetStream = vp.SaveAsset(pcAsset))
                    {
                        fs.CopyTo(assetStream);
                    }
                }
            }
        }
Пример #9
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                AuthorizationState authzState = null;
                var ii = new IdentifierInfo
                {
                    Id              = EntityHelper.NewId(),
                    Alias           = Alias,
                    Label           = Label,
                    Memo            = Memo,
                    RegistrationRef = ri.Id,
                    Dns             = Dns,
                };

                using (var c = ClientHelper.GetClient(v, ri))
                {
                    c.Init();
                    c.GetDirectory(true);

                    authzState       = c.AuthorizeIdentifier(Dns);
                    ii.Authorization = authzState;

                    if (v.Identifiers == null)
                    {
                        v.Identifiers = new EntityDictionary <IdentifierInfo>();
                    }

                    v.Identifiers.Add(ii);
                }

                vp.SaveVault(v);

                WriteObject(authzState);
            }
        }
Пример #10
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                WriteObject(r);
            }
        }
Пример #11
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Identifiers == null || v.Identifiers.Count < 1)
                {
                    throw new InvalidOperationException("No identifiers found");
                }

                var ii = v.Identifiers.GetByRef(Ref);
                if (ii == null)
                {
                    throw new Exception("Unable to find an Identifier for the given reference");
                }

                var authzState = ii.Authorization;

                using (var c = ClientHelper.GetClient(v, ri))
                {
                    c.Init();
                    c.GetDirectory(true);

                    var challenge = c.SubmitAuthorizeChallengeAnswer(authzState, Challenge, UseBaseURI);
                    ii.Challenges[Challenge] = challenge;
                }

                vp.SaveVault(v);

                WriteObject(authzState);
            }
        }
Пример #12
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Identifiers == null || v.Identifiers.Count < 1)
                {
                    throw new InvalidOperationException("No identifiers found");
                }

                if (string.IsNullOrEmpty(Ref))
                {
                    int seq = 0;
                    WriteObject(v.Identifiers.Values.Select(x => new
                    {
                        Seq    = seq++,
                        Id     = x.Id,
                        Alias  = x.Alias,
                        Label  = x.Label,
                        Dns    = x.Dns,
                        Status = x.Authorization.Status
                    }), true);
                }
                else
                {
                    var ii = v.Identifiers.GetByRef(Ref);
                    if (ii == null)
                    {
                        throw new ItemNotFoundException("Unable to find an Identifier for the given reference");
                    }

                    var authzState = ii.Authorization;

                    WriteObject(authzState);
                }
            }
        }
Пример #13
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (GetInitialDirectory.HasValue)
                {
                    v.GetInitialDirectory = GetInitialDirectory.Value;
                }

                if (UseRelativeInitialDirectory.HasValue)
                {
                    v.UseRelativeInitialDirectory = UseRelativeInitialDirectory.Value;
                }

                if (!string.IsNullOrEmpty(IssuerCert))
                {
                    SetResEntry(v.ServerDirectory, AcmeServerDirectory.RES_ISSUER_CERT, IssuerCert);
                }

                if (!string.IsNullOrEmpty(Resource) && !string.IsNullOrEmpty(Resource))
                {
                    SetResEntry(v.ServerDirectory, Resource, Path);
                }

                if (ResourceMap != null)
                {
                    foreach (var ent in ResourceMap)
                    {
                        var dent = (DictionaryEntry)ent;
                        SetResEntry(v.ServerDirectory, dent.Key as string, dent.Value as string);
                    }
                }

                vp.SaveVault(v);
            }
        }
Пример #14
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                AcmeRegistration r = null;
                var ri             = new RegistrationInfo
                {
                    Id             = EntityHelper.NewId(),
                    Alias          = Alias,
                    Label          = Label,
                    Memo           = Memo,
                    SignerProvider = Signer,
                };

                using (var c = ClientHelper.GetClient(v, ri))
                {
                    c.Init();
                    c.GetDirectory(true);

                    r = c.Register(Contacts);
                    ri.Registration = r;

                    if (v.Registrations == null)
                    {
                        v.Registrations = new EntityDictionary <RegistrationInfo>();
                    }

                    v.Registrations.Add(ri);
                }

                vp.SaveVault(v);

                WriteObject(r);
            }
        }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (!LocalOnly)
                {
                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        r = c.UpdateRegistration(UseBaseURI, AcceptTOS, Contacts);
                        ri.Registration = r;
                    }

                    vp.SaveVault(v);
                }

                v.Alias = StringHelper.IfNullOrEmpty(Alias);
                v.Label = StringHelper.IfNullOrEmpty(Label);
                v.Memo  = StringHelper.IfNullOrEmpty(Memo);

                vp.SaveVault(v);

                WriteObject(r);
            }
        }
Пример #16
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Identifiers == null || v.Identifiers.Count < 1)
                {
                    throw new InvalidOperationException("No identifiers found");
                }

                var ii = v.Identifiers.GetByRef(Ref);
                if (ii == null)
                {
                    throw new Exception("Unable to find an Identifier for the given reference");
                }

                var authzState = ii.Authorization;

                if (ii.Challenges == null)
                {
                    ii.Challenges = new Dictionary <string, AuthorizeChallenge>();
                }

                if (ii.ChallengeCompleted == null)
                {
                    ii.ChallengeCompleted = new Dictionary <string, DateTime?>();
                }

                if (v.ProviderConfigs == null || v.ProviderConfigs.Count < 1)
                {
                    throw new InvalidOperationException("No provider configs found");
                }

                var pc = v.ProviderConfigs.GetByRef(ProviderConfig);
                if (pc == null)
                {
                    throw new InvalidOperationException("Unable to find a Provider Config for the given reference");
                }
                var pcFilePath = Path.GetFullPath($"{pc.Id}.json");

                AuthorizeChallenge challenge         = null;
                DateTime?          challengCompleted = null;
                ii.Challenges.TryGetValue(Challenge, out challenge);
                ii.ChallengeCompleted.TryGetValue(Challenge, out challengCompleted);

                if (challenge == null || Regenerate)
                {
                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        challenge = c.GenerateAuthorizeChallengeAnswer(authzState, Challenge);
                        ii.Challenges[Challenge] = challenge;
                    }
                }

                if (Repeat || challengCompleted == null)
                {
                    if (Challenge == "dns")
                    {
                        if (string.IsNullOrEmpty(pc.DnsProvider))
                        {
                            throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge");
                        }

                        var dnsName   = challenge.ChallengeAnswer.Key;
                        var dnsValue  = Regex.Replace(challenge.ChallengeAnswer.Value, "\\s", "");
                        var dnsValues = Regex.Replace(dnsValue, "(.{100,100})", "$1\n").Split('\n');

                        using (var fs = new FileStream(pcFilePath, FileMode.Open))
                        {
                            var dnsInfo = DnsInfo.Load(fs);
                            dnsInfo.Provider.EditTxtRecord(dnsName, dnsValues);
                            ii.ChallengeCompleted[Challenge] = DateTime.Now;
                        }
                    }
                    else if (Challenge == "simpleHttp")
                    {
                        if (string.IsNullOrEmpty(pc.WebServerProvider))
                        {
                            throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge");
                        }

                        var wsFilePath = challenge.ChallengeAnswer.Key;
                        var wsFileBody = challenge.ChallengeAnswer.Value;
                        var wsFileUrl  = new Uri($"http://{authzState.Identifier}/{wsFilePath}");

                        using (var fs = new FileStream(pcFilePath, FileMode.Open))
                        {
                            var webServerInfo = WebServerInfo.Load(fs);
                            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(wsFileBody)))
                            {
                                webServerInfo.Provider.UploadFile(wsFileUrl, ms);
                                ii.ChallengeCompleted[Challenge] = DateTime.Now;
                            }
                        }
                    }
                }

                vp.SaveVault(v);

                WriteObject(authzState);
            }
        }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                {
                    throw new InvalidOperationException("No certificates found");
                }

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                {
                    throw new Exception("Unable to find a Certificate for the given reference");
                }

                if (!LocalOnly)
                {
                    if (ci.CertificateRequest == null)
                    {
                        throw new Exception("Certificate has not been submitted yet; cannot update status");
                    }

                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        c.RefreshCertificateRequest(ci.CertificateRequest, UseBaseURI);
                    }

                    if ((Repeat || string.IsNullOrEmpty(ci.CrtPemFile)) &&
                        !string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                    {
                        var fileMode = Repeat ? FileMode.Create : FileMode.CreateNew;

                        var crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

                        using (var fs = new FileStream(crtDerFile, fileMode))
                        {
                            ci.CertificateRequest.SaveCertificate(fs);
                            ci.CrtDerFile = crtDerFile;
                        }

                        CsrHelper.Crt.ConvertDerToPem(crtDerFile, crtPemFile, fileMode);
                        ci.CrtPemFile = crtPemFile;

                        var crt = new X509Certificate2(crtDerFile);

                        ci.SerialNumber       = crt.SerialNumber;
                        ci.Thumbprint         = crt.Thumbprint;
                        ci.SignatureAlgorithm = crt.SignatureAlgorithm?.FriendlyName;
                        ci.Signature          = crt.GetCertHashString();
                    }

                    if (Repeat || string.IsNullOrEmpty(ci.IssuerSerialNumber))
                    {
                        var linksEnum = ci.CertificateRequest.Links;
                        if (linksEnum != null)
                        {
                            var links  = new LinkCollection(linksEnum);
                            var upLink = links.GetFirstOrDefault("up");
                            if (upLink != null)
                            {
                                var tmp = Path.GetTempFileName();
                                try
                                {
                                    using (var web = new WebClient())
                                    {
                                        if (v.Proxy != null)
                                        {
                                            web.Proxy = v.Proxy.GetWebProxy();
                                        }

                                        var uri = new Uri(new Uri(v.BaseURI), upLink.Uri);
                                        web.DownloadFile(uri, tmp);
                                    }

                                    var cacert = new X509Certificate2(tmp);
                                    var sernum = cacert.GetSerialNumberString();
                                    var tprint = cacert.Thumbprint;
                                    var sigalg = cacert.SignatureAlgorithm?.FriendlyName;
                                    var sigval = cacert.GetCertHashString();

                                    if (v.IssuerCertificates == null)
                                    {
                                        v.IssuerCertificates = new OrderedNameMap <IssuerCertificateInfo>();
                                    }
                                    if (!v.IssuerCertificates.ContainsKey(sernum))
                                    {
                                        var cacertDerFile = $"ca-{sernum}-crt.der";
                                        var cacertPemFile = $"ca-{sernum}-crt.pem";

                                        if (Repeat || !File.Exists(cacertDerFile))
                                        {
                                            File.Copy(tmp, cacertDerFile, true);
                                        }
                                        if (Repeat || !File.Exists(cacertPemFile))
                                        {
                                            CsrHelper.Crt.ConvertDerToPem(cacertDerFile, cacertPemFile);
                                        }

                                        v.IssuerCertificates[sernum] = new IssuerCertificateInfo
                                        {
                                            SerialNumber       = sernum,
                                            Thumbprint         = tprint,
                                            SignatureAlgorithm = sigalg,
                                            Signature          = sigval,
                                            CrtDerFile         = cacertDerFile,
                                            CrtPemFile         = cacertPemFile,
                                        };
                                    }

                                    ci.IssuerSerialNumber = sernum;
                                }
                                finally
                                {
                                    if (File.Exists(tmp))
                                    {
                                        File.Delete(tmp);
                                    }
                                }
                            }
                        }
                    }
                }

                v.Alias = StringHelper.IfNullOrEmpty(Alias);
                v.Label = StringHelper.IfNullOrEmpty(Label);
                v.Memo  = StringHelper.IfNullOrEmpty(Memo);

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider())
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                {
                    throw new InvalidOperationException("No certificates found");
                }

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                {
                    throw new Exception("Unable to find a Certificate for the given reference");
                }

                if (!string.IsNullOrEmpty(ci.GenerateDetailsFile))
                {
                    // Generate a private key and CSR:
                    //    Key:  RSA 2048-bit
                    //    MD:   SHA 256
                    //    CSR:  Details pulled from CSR Details JSON file

                    CsrHelper.CsrDetails csrDetails;
                    using (var fs = new FileStream(Path.GetFullPath(ci.GenerateDetailsFile),
                                                   FileMode.Open))
                    {
                        csrDetails = JsonHelper.Load <CsrHelper.CsrDetails>(fs);
                    }

                    var keyGenFile = $"{ci.Id}-gen-key.json";
                    var keyPemFile = $"{ci.Id}-key.pem";
                    var csrGenFile = $"{ci.Id}-gen-csr.json";
                    var csrPemFile = $"{ci.Id}-csr.pem";

                    var genKey = CsrHelper.GenerateRsaPrivateKey();
                    using (var fs = new FileStream(keyGenFile, FileMode.CreateNew))
                    {
                        genKey.Save(fs);
                        File.WriteAllText(keyPemFile, genKey.Pem);
                    }

                    var genCsr = CsrHelper.GenerateCsr(csrDetails, genKey);
                    using (var fs = new FileStream(csrGenFile, FileMode.CreateNew))
                    {
                        genCsr.Save(fs);
                        File.WriteAllText(csrPemFile, genCsr.Pem);
                    }

                    ci.KeyPemFile = keyPemFile;
                    ci.CsrPemFile = csrPemFile;
                }

                byte[] derRaw;
                using (var fs = new FileStream(ci.CsrPemFile, FileMode.Open))
                {
                    using (var ms = new MemoryStream())
                    {
                        CsrHelper.Csr.ConvertPemToDer(fs, ms);
                        derRaw = ms.ToArray();
                    }
                }

                var derB64u = JwsHelper.Base64UrlEncode(derRaw);

                using (var c = ClientHelper.GetClient(v, ri))
                {
                    c.Init();
                    c.GetDirectory(true);

                    ci.CertificateRequest = c.RequestCertificate(derB64u);
                }

                if (!string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                {
                    var crtDerFile = $"{ci.Id}-crt.der";
                    var crtPemFile = $"{ci.Id}-crt.pem";

                    using (var fs = new FileStream(crtDerFile, FileMode.CreateNew))
                    {
                        ci.CertificateRequest.SaveCertificate(fs);
                        ci.CrtDerFile = crtDerFile;
                    }

                    using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                           target = new FileStream(crtPemFile, FileMode.CreateNew))
                    {
                        CsrHelper.Crt.ConvertDerToPem(source, target);
                        ci.CrtPemFile = crtPemFile;
                    }
                }

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
Пример #19
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                {
                    throw new InvalidOperationException("No certificates found");
                }

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                {
                    throw new ItemNotFoundException("Unable to find a Certificate for the given reference");
                }

                var mode = Overwrite ? FileMode.Create : FileMode.CreateNew;

                if (!string.IsNullOrEmpty(ExportKeyPEM))
                {
                    if (string.IsNullOrEmpty(ci.KeyPemFile))
                    {
                        throw new InvalidOperationException("Cannot export private key; it hasn't been imported or generated");
                    }
                    CopyTo(vp, VaultAssetType.KeyPem, ci.KeyPemFile, ExportKeyPEM, mode);
                }

                if (!string.IsNullOrEmpty(ExportCsrPEM))
                {
                    if (string.IsNullOrEmpty(ci.CsrPemFile))
                    {
                        throw new InvalidOperationException("Cannot export CSR; it hasn't been imported or generated");
                    }
                    CopyTo(vp, VaultAssetType.CsrPem, ci.CsrPemFile, ExportCsrPEM, mode);
                }

                if (!string.IsNullOrEmpty(ExportCertificatePEM))
                {
                    if (ci.CertificateRequest == null || string.IsNullOrEmpty(ci.CrtPemFile))
                    {
                        throw new InvalidOperationException("Cannot export CRT; CSR hasn't been submitted or CRT hasn't been retrieved");
                    }
                    CopyTo(vp, VaultAssetType.CrtPem, ci.CrtPemFile, ExportCertificatePEM, mode);
                }

                if (!string.IsNullOrEmpty(ExportCertificateDER))
                {
                    if (ci.CertificateRequest == null || string.IsNullOrEmpty(ci.CrtDerFile))
                    {
                        throw new InvalidOperationException("Cannot export CRT; CSR hasn't been submitted or CRT hasn't been retrieved");
                    }
                    CopyTo(vp, VaultAssetType.CrtDer, ci.CrtDerFile, ExportCertificateDER, mode);
                }

                if (!string.IsNullOrEmpty(ExportPkcs12))
                {
                    if (string.IsNullOrEmpty(ci.KeyPemFile))
                    {
                        throw new InvalidOperationException("Cannot export PKCS12; private hasn't been imported or generated");
                    }
                    if (string.IsNullOrEmpty(ci.CrtPemFile))
                    {
                        throw new InvalidOperationException("Cannot export PKCS12; CSR hasn't been submitted or CRT hasn't been retrieved");
                    }
                    if (string.IsNullOrEmpty(ci.IssuerSerialNumber) || !v.IssuerCertificates.ContainsKey(ci.IssuerSerialNumber))
                    {
                        throw new InvalidOperationException("Cannot export PKCS12; Issuer certificate hasn't been resolved");
                    }

                    var keyPemAsset = vp.GetAsset(VaultAssetType.KeyPem, ci.KeyPemFile);
                    var crtPemAsset = vp.GetAsset(VaultAssetType.CrtPem, ci.CrtPemFile);
                    var isuPemAsset = vp.GetAsset(VaultAssetType.IssuerPem,
                                                  v.IssuerCertificates[ci.IssuerSerialNumber].CrtPemFile);

                    using (Stream keyStream = vp.LoadAsset(keyPemAsset),
                           crtStream = vp.LoadAsset(crtPemAsset),
                           isuStream = vp.LoadAsset(isuPemAsset),
                           fs = new FileStream(ExportPkcs12, mode))
                    {
                        CsrHelper.Crt.ConvertToPfx(keyStream, crtStream, isuStream, fs);
                    }
                }

                WriteObject(ci);
            }
        }
Пример #20
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Certificates == null || v.Certificates.Count < 1)
                {
                    throw new InvalidOperationException("No certificates found");
                }

                var ci = v.Certificates.GetByRef(Ref);
                if (ci == null)
                {
                    throw new Exception("Unable to find a Certificate for the given reference");
                }

                if (!string.IsNullOrEmpty(ci.GenerateDetailsFile))
                {
                    // Generate a private key and CSR:
                    //    Key:  RSA 2048-bit
                    //    MD:   SHA 256
                    //    CSR:  Details pulled from CSR Details JSON file

                    CsrHelper.CsrDetails csrDetails;
                    var csrDetailsAsset = vp.GetAsset(VaultAssetType.CsrDetails, ci.GenerateDetailsFile);
                    using (var s = vp.LoadAsset(csrDetailsAsset))
                    {
                        csrDetails = JsonHelper.Load <CsrHelper.CsrDetails>(s);
                    }

                    var keyGenFile = $"{ci.Id}-gen-key.json";
                    var keyPemFile = $"{ci.Id}-key.pem";
                    var csrGenFile = $"{ci.Id}-gen-csr.json";
                    var csrPemFile = $"{ci.Id}-csr.pem";

                    var keyGenAsset = vp.CreateAsset(VaultAssetType.KeyGen, keyGenFile);
                    var keyPemAsset = vp.CreateAsset(VaultAssetType.KeyPem, keyPemFile);
                    var csrGenAsset = vp.CreateAsset(VaultAssetType.CsrGen, csrGenFile);
                    var csrPemAsset = vp.CreateAsset(VaultAssetType.CsrPem, csrPemFile);

                    var genKey = CsrHelper.GenerateRsaPrivateKey();
                    using (var s = vp.SaveAsset(keyGenAsset))
                    {
                        genKey.Save(s);
                    }
                    using (var w = new StreamWriter(vp.SaveAsset(keyPemAsset)))
                    {
                        w.Write(genKey.Pem);
                    }

                    var genCsr = CsrHelper.GenerateCsr(csrDetails, genKey);
                    using (var s = vp.SaveAsset(csrGenAsset))
                    {
                        genCsr.Save(s);
                    }
                    using (var w = new StreamWriter(vp.SaveAsset(csrPemAsset)))
                    {
                        w.Write(genCsr.Pem);
                    }

                    ci.KeyPemFile = keyPemFile;
                    ci.CsrPemFile = csrPemFile;
                }

                var asset = vp.GetAsset(VaultAssetType.CsrPem, ci.CsrPemFile);

                byte[] derRaw;
                using (var s = vp.LoadAsset(asset))
                {
                    using (var ms = new MemoryStream())
                    {
                        CsrHelper.Csr.ConvertPemToDer(s, ms);
                        derRaw = ms.ToArray();
                    }
                }

                var derB64u = JwsHelper.Base64UrlEncode(derRaw);

                using (var c = ClientHelper.GetClient(v, ri))
                {
                    c.Init();
                    c.GetDirectory(true);

                    ci.CertificateRequest = c.RequestCertificate(derB64u);
                }

                if (!string.IsNullOrEmpty(ci.CertificateRequest.CertificateContent))
                {
                    var crtDerFile = $"{ci.Id}-crt.der";
                    var crtPemFile = $"{ci.Id}-crt.pem";

                    var crtDerAsset = vp.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                    var crtPemAsset = vp.CreateAsset(VaultAssetType.CrtPem, crtPemFile);

                    using (var s = vp.SaveAsset(crtDerAsset))
                    {
                        ci.CertificateRequest.SaveCertificate(s);
                        ci.CrtDerFile = crtDerFile;
                    }

                    using (Stream source = vp.LoadAsset(crtDerAsset), target = vp.SaveAsset(crtPemAsset))
                    {
                        CsrHelper.Crt.ConvertDerToPem(source, target);
                        ci.CrtPemFile = crtPemFile;
                    }

                    var crt = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                    ci.SerialNumber       = crt.SerialNumber;
                    ci.Thumbprint         = crt.Thumbprint;
                    ci.SignatureAlgorithm = crt.SignatureAlgorithm?.FriendlyName;
                    ci.Signature          = crt.GetCertHashString();
                }

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
Пример #21
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Identifiers == null || v.Identifiers.Count < 1)
                {
                    throw new InvalidOperationException("No identifiers found");
                }

                var ii = v.Identifiers.GetByRef(Identifier);
                if (ii == null)
                {
                    throw new Exception("Unable to find an Identifier for the given reference");
                }

                var ci = new CertificateInfo
                {
                    Id            = EntityHelper.NewId(),
                    Alias         = Alias,
                    Label         = Label,
                    Memo          = Memo,
                    IdentifierRef = ii.Id,
                };

                if (Generate)
                {
                    var csrDetails = new CsrHelper.CsrDetails
                    {
                        CommonName = ii.Dns,
                    };

                    ci.GenerateDetailsFile = $"{ci.Id}-gen.json";
                    var asset = vp.CreateAsset(VaultAssetType.CsrDetails, ci.GenerateDetailsFile);
                    using (var s = vp.SaveAsset(asset))
                    {
                        JsonHelper.Save(s, csrDetails);
                    }
                }
                else
                {
                    if (!File.Exists(KeyPemFile))
                    {
                        throw new FileNotFoundException("Missing specified RSA Key file path");
                    }
                    if (!File.Exists(CsrPemFile))
                    {
                        throw new FileNotFoundException("Missing specified CSR details file path");
                    }

                    var keyPemFile = $"{ci.Id}-key.pem";
                    var csrPemFile = $"{ci.Id}-csr.pem";

                    var keyAsset = vp.CreateAsset(VaultAssetType.KeyPem, keyPemFile, true);
                    var csrAsset = vp.CreateAsset(VaultAssetType.CsrPem, csrPemFile);

                    using (Stream fs = new FileStream(KeyPemFile, FileMode.Open),
                           s = vp.SaveAsset(keyAsset))
                    {
                        fs.CopyTo(s);
                    }
                    using (Stream fs = new FileStream(KeyPemFile, FileMode.Open),
                           s = vp.SaveAsset(csrAsset))
                    {
                        fs.CopyTo(s);
                    }

                    ci.KeyPemFile = keyPemFile;
                    ci.CsrPemFile = csrPemFile;
                }

                if (v.Certificates == null)
                {
                    v.Certificates = new EntityDictionary <CertificateInfo>();
                }

                v.Certificates.Add(ci);

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
Пример #22
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage();
                var v = vp.LoadVault();

                if (v.Registrations == null || v.Registrations.Count < 1)
                {
                    throw new InvalidOperationException("No registrations found");
                }

                var ri = v.Registrations[0];
                var r  = ri.Registration;

                if (v.Identifiers == null || v.Identifiers.Count < 1)
                {
                    throw new InvalidOperationException("No identifiers found");
                }

                var ii = v.Identifiers.GetByRef(Ref);
                if (ii == null)
                {
                    throw new Exception("Unable to find an Identifier for the given reference");
                }

                var authzState = ii.Authorization;

                if (ii.Challenges == null)
                {
                    ii.Challenges = new Dictionary <string, AuthorizeChallenge>();
                }

                if (ii.ChallengeCompleted == null)
                {
                    ii.ChallengeCompleted = new Dictionary <string, DateTime?>();
                }

                if (v.ProviderConfigs == null || v.ProviderConfigs.Count < 1)
                {
                    throw new InvalidOperationException("No provider configs found");
                }

                var pc = v.ProviderConfigs.GetByRef(ProviderConfig);
                if (pc == null)
                {
                    throw new InvalidOperationException("Unable to find a Provider Config for the given reference");
                }

                AuthorizeChallenge challenge         = null;
                DateTime?          challengCompleted = null;
                ii.Challenges.TryGetValue(Challenge, out challenge);
                ii.ChallengeCompleted.TryGetValue(Challenge, out challengCompleted);

                if (challenge == null || Regenerate)
                {
                    using (var c = ClientHelper.GetClient(v, ri))
                    {
                        c.Init();
                        c.GetDirectory(true);

                        challenge = c.GenerateAuthorizeChallengeAnswer(authzState, Challenge);
                        ii.Challenges[Challenge] = challenge;
                    }
                }

                if (Repeat || challengCompleted == null)
                {
                    var pcFilePath = $"{pc.Id}.json";
                    var pcAsset    = vp.GetAsset(Vault.VaultAssetType.ProviderConfigInfo, pcFilePath);

                    // TODO:  There's *way* too much logic buried in here
                    // this needs to be refactored and extracted out to be
                    // more manageble and more reusable

                    if (Challenge == AcmeProtocol.CHALLENGE_TYPE_DNS ||
                        Challenge == AcmeProtocol.CHALLENGE_TYPE_LEGACY_DNS)
                    {
                        if (string.IsNullOrEmpty(pc.DnsProvider))
                        {
                            throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge");
                        }

                        var dnsName   = challenge.ChallengeAnswer.Key;
                        var dnsValue  = Regex.Replace(challenge.ChallengeAnswer.Value, "\\s", "");
                        var dnsValues = Regex.Replace(dnsValue, "(.{100,100})", "$1\n").Split('\n');

                        using (var s = vp.LoadAsset(pcAsset)) // new FileStream(pcFilePath, FileMode.Open))
                        {
                            var dnsInfo = DnsInfo.Load(s);
                            dnsInfo.Provider.EditTxtRecord(dnsName, dnsValues);
                            ii.ChallengeCompleted[Challenge] = DateTime.Now;
                        }
                    }
                    else if (Challenge == AcmeProtocol.CHALLENGE_TYPE_HTTP ||
                             Challenge == AcmeProtocol.CHALLENGE_TYPE_LEGACY_HTTP)
                    {
                        if (string.IsNullOrEmpty(pc.WebServerProvider))
                        {
                            throw new InvalidOperationException("Referenced Provider Configuration does not support the selected Challenge");
                        }

                        var wsFilePath = challenge.ChallengeAnswer.Key;
                        var wsFileBody = challenge.ChallengeAnswer.Value;
                        var wsFileUrl  = new Uri($"http://{authzState.Identifier}/{wsFilePath}");



                        using (var s = vp.LoadAsset(pcAsset)) // new FileStream(pcFilePath, FileMode.Open))
                        {
                            var webServerInfo = WebServerInfo.Load(s);
                            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(wsFileBody)))
                            {
                                webServerInfo.Provider.UploadFile(wsFileUrl, ms);
                                ii.ChallengeCompleted[Challenge] = DateTime.Now;
                            }
                        }
                    }
                }

                vp.SaveVault(v);

                WriteObject(authzState);
            }
        }