Example #1
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                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);
            }
        }
Example #2
0
        protected override void ProcessRecord()
        {
            var pc = new ProviderConfig
            {
                Id                = EntityHelper.NewId(),
                Alias             = Alias,
                Label             = Label,
                Memo              = Memo,
                DnsProvider       = DnsProvider,
                WebServerProvider = WebServerProvider,
            };

            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                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 = ProviderConfigSamples.Loader.LoadDnsProviderConfig(
                        DnsProvider);
                }
                if (!string.IsNullOrEmpty(WebServerProvider))
                {
                    s = ProviderConfigSamples.Loader.LoadWebServerProviderConfig(
                        WebServerProvider);
                }

                var temp = Path.GetTempFileName();
                using (var fs = new FileStream(temp, FileMode.Create))
                {
                    s.CopyTo(fs);
                }
                EditFile(temp, EditWith);

                var pcAsset = vp.CreateAsset(VaultAssetType.ProviderConfigInfo, $"{pc.Id}.json");
                using (Stream fs = new FileStream(temp, FileMode.Open),
                       assetStream = vp.SaveAsset(pcAsset))
                {
                    fs.CopyTo(assetStream);
                }
                File.Delete(temp);

                s.Close();
                s.Dispose();
            }
        }
Example #3
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);
            }
        }
        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]);
                }
            }
        }
Example #5
0
        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");
                    using (var temp = new TemporaryFile())
                    {
                        using (var s = vp.LoadAsset(pcAsset))
                        {
                            using (var fs = new FileStream(temp.FileName, FileMode.Create))
                            {
                                s.CopyTo(fs);
                            }
                        }
                        NewProviderConfig.EditFile(temp.FileName, EditWith);

                        using (Stream fs = new FileStream(temp.FileName, FileMode.Open),
                               assetStream = vp.SaveAsset(pcAsset))
                        {
                            fs.CopyTo(assetStream);
                        }
                    }
                }
            }
        }
Example #6
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;

                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);
            }
        }
Example #7
0
        public bool InitVault(bool staging = true)
        {
            string apiURI = InitializeVault.WELL_KNOWN_BASE_SERVICES[InitializeVault.WELL_KNOWN_LESTAGE];

            if (!staging)
            {
                //live api
                apiURI = InitializeVault.WELL_KNOWN_BASE_SERVICES[InitializeVault.WELL_KNOWN_LE];
            }

            bool vaultExists = false;

            using (var vlt = ACMESharp.POSH.Util.VaultHelper.GetVault())
            {
                vlt.OpenStorage(true);
                var v = vlt.LoadVault(false);
                if (v != null)
                {
                    vaultExists = true;
                }
            }

            if (!vaultExists)
            {
                if (UsePowershell)
                {
                    powershellManager.InitializeVault(apiURI);
                }
                else
                {
                    var cmd = new ACMESharp.POSH.InitializeVault();
                    cmd.BaseUri = apiURI;
                    cmd.ExecuteCommand();
                }
            }
            else
            {
                this.LogAction("InitVault", "Vault exists.");
            }

            this.vaultFolderPath = GetVaultPath();

            //create default manual http provider (challenge/response by placing answer in well known location on website for server to fetch);
            //powershellManager.NewProviderConfig("Manual", "manualHttpProvider");
            return(true);
        }
Example #8
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;

                WriteObject(r);
            }
        }
Example #9
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);
                    if (AcceptTos)
                    {
                        r = c.UpdateRegistration(agreeToTos: true);
                    }

                    ri.Registration = r;

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

                    v.Registrations.Add(ri);
                }

                vp.SaveVault(v);

                WriteObject(r);
            }
        }
Example #10
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);
            }
        }
Example #11
0
        protected override void ProcessRecord()
        {
            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                vp.OpenStorage(Force);
                var v = vp.LoadVault();

                var baseUri = BaseUri;
                if (string.IsNullOrEmpty(baseUri) && !string.IsNullOrEmpty(BaseService))
                {
                    baseUri = InitializeVault.WELL_KNOWN_BASE_SERVICES[BaseService];
                }

                v.Alias       = StringHelper.IfNullOrEmpty(Alias, v.Alias);
                v.Label       = StringHelper.IfNullOrEmpty(Label, v.Label);
                v.Memo        = StringHelper.IfNullOrEmpty(Memo, v.Memo);
                v.BaseService = StringHelper.IfNullOrEmpty(BaseService, v.BaseService);
                v.BaseUri     = StringHelper.IfNullOrEmpty(baseUri, v.BaseUri);

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

                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
                {
                    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 ItemNotFoundException("Unable to find an Identifier for the given reference");
                    }

                    var authzState = ii.Authorization;

                    WriteObject(authzState);
                }
            }
        }
Example #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);
            }
        }
Example #14
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 (!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);
            }
        }
Example #15
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 (!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 crtDerFile = $"{ci.Id}-crt.der";
                        var crtPemFile = $"{ci.Id}-crt.pem";

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

                        if (crtDerAsset == null)
                        {
                            crtDerAsset = vp.CreateAsset(VaultAssetType.CrtDer, crtDerFile);
                        }
                        if (crtPemAsset == null)
                        {
                            crtPemAsset = vp.CreateAsset(VaultAssetType.CrtPem, crtPemFile);
                        }

                        using (var cp = CertificateProvider.GetProvider())
                        {
                            var bytes = ci.CertificateRequest.GetCertificateContent();

                            using (Stream source = new MemoryStream(bytes),
                                   derTarget = vp.SaveAsset(crtDerAsset),
                                   pemTarget = vp.SaveAsset(crtPemAsset))
                            {
                                var crt = cp.ImportCertificate(EncodingFormat.DER, source);

                                // We're saving the DER format cert "through"
                                // the CP in order to validate its content
                                cp.ExportCertificate(crt, EncodingFormat.DER, derTarget);
                                ci.CrtDerFile = crtDerFile;

                                cp.ExportCertificate(crt, EncodingFormat.PEM, pemTarget);
                                ci.CrtPemFile = crtPemFile;
                            }
                        }

                        var x509 = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber       = x509.SerialNumber;
                        ci.Thumbprint         = x509.Thumbprint;
                        ci.SignatureAlgorithm = x509.SignatureAlgorithm?.FriendlyName;
                        ci.Signature          = x509.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)
                            {
                                // We need to save the ICA certificate to a local
                                // temp file so that we can read it in and store
                                // it properly as a vault asset through a stream
                                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 (Repeat || !v.IssuerCertificates.ContainsKey(sernum))
                                    {
                                        var cacertDerFile  = $"ca-{sernum}-crt.der";
                                        var cacertPemFile  = $"ca-{sernum}-crt.pem";
                                        var issuerDerAsset = vp.ListAssets(cacertDerFile,
                                                                           VaultAssetType.IssuerDer).FirstOrDefault();
                                        var issuerPemAsset = vp.ListAssets(cacertPemFile,
                                                                           VaultAssetType.IssuerPem).FirstOrDefault();

                                        if (Repeat || issuerDerAsset == null)
                                        {
                                            if (issuerDerAsset == null)
                                            {
                                                issuerDerAsset = vp.CreateAsset(VaultAssetType.IssuerDer, cacertDerFile);
                                            }
                                            using (Stream fs = new FileStream(tmp, FileMode.Open),
                                                   s = vp.SaveAsset(issuerDerAsset))
                                            {
                                                fs.CopyTo(s);
                                            }
                                        }
                                        if (Repeat || issuerPemAsset == null)
                                        {
                                            if (issuerPemAsset == null)
                                            {
                                                issuerPemAsset = vp.CreateAsset(VaultAssetType.IssuerPem, cacertPemFile);
                                            }

                                            using (var cp = CertificateProvider.GetProvider())
                                            {
                                                using (Stream source = vp.LoadAsset(issuerDerAsset),
                                                       target = vp.SaveAsset(issuerPemAsset))
                                                {
                                                    var crt = cp.ImportCertificate(EncodingFormat.DER, source);
                                                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                                                }
                                            }
                                        }

                                        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);
            }
        }
Example #16
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 (string.IsNullOrEmpty(Ref))
                {
                    int seq = 0;
                    WriteObject(v.Certificates.Values.Select(x => new
                    {
                        Seq         = seq++,
                        Certificate = x,
                        //Id = x.Id,
                        //Alias = x.Alias,
                        //Label = x.Label,
                        //StatusCode = x.CertificateRequest.StatusCode
                    }), true);
                }
                else
                {
                    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 (var cp = CertificateProvider.GetProvider())
                        {
                            using (Stream keyStream = vp.LoadAsset(keyPemAsset),
                                   crtStream = vp.LoadAsset(crtPemAsset),
                                   isuStream = vp.LoadAsset(isuPemAsset),
                                   fs = new FileStream(ExportPkcs12, mode))
                            {
                                var pk  = cp.ImportPrivateKey <RsaPrivateKey>(EncodingFormat.PEM, keyStream);
                                var crt = cp.ImportCertificate(EncodingFormat.PEM, crtStream);
                                var isu = cp.ImportCertificate(EncodingFormat.PEM, isuStream);

                                var certs = new[] { crt, isu };

                                var password = string.IsNullOrWhiteSpace(CertificatePassword)
                                    ? string.Empty
                                    : CertificatePassword;

                                cp.ExportArchive(pk, certs, ArchiveFormat.PKCS12, fs, password);
                            }
                        }
                    }

                    WriteObject(ci);
                }
            }
        }
Example #17
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 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);
            }
        }
Example #18
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");
                }

                using (var cp = CertificateProvider.GetProvider())
                {
                    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

                        CsrDetails csrDetails;
                        var        csrDetailsAsset = vp.GetAsset(VaultAssetType.CsrDetails, ci.GenerateDetailsFile);
                        using (var s = vp.LoadAsset(csrDetailsAsset))
                        {
                            csrDetails = JsonHelper.Load <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 genKeyParams = new RsaPrivateKeyParams();

                        var genKey = cp.GeneratePrivateKey(genKeyParams);
                        using (var s = vp.SaveAsset(keyGenAsset))
                        {
                            cp.SavePrivateKey(genKey, s);
                        }
                        using (var s = vp.SaveAsset(keyPemAsset))
                        {
                            cp.ExportPrivateKey(genKey, EncodingFormat.PEM, s);
                        }

                        // TODO: need to surface details of the CSR params up higher
                        var csrParams = new CsrParams
                        {
                            Details = csrDetails
                        };
                        var genCsr = cp.GenerateCsr(csrParams, genKey, Crt.MessageDigest.SHA256);
                        using (var s = vp.SaveAsset(csrGenAsset))
                        {
                            cp.SaveCsr(genCsr, s);
                        }
                        using (var s = vp.SaveAsset(csrPemAsset))
                        {
                            cp.ExportCsr(genCsr, EncodingFormat.PEM, s);
                        }

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



                    byte[] derRaw;

                    var asset = vp.GetAsset(VaultAssetType.CsrPem, ci.CsrPemFile);
                    // Convert the stored CSR in PEM format to DER
                    using (var source = vp.LoadAsset(asset))
                    {
                        var csr = cp.ImportCsr(EncodingFormat.PEM, source);
                        using (var target = new MemoryStream())
                        {
                            cp.ExportCsr(csr, EncodingFormat.DER, target);
                            derRaw = target.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 crtDerBytes = ci.CertificateRequest.GetCertificateContent();

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

                        using (Stream source = new MemoryStream(crtDerBytes),
                               derTarget = vp.SaveAsset(crtDerAsset),
                               pemTarget = vp.SaveAsset(crtPemAsset))
                        {
                            var crt = cp.ImportCertificate(EncodingFormat.DER, source);

                            cp.ExportCertificate(crt, EncodingFormat.DER, derTarget);
                            ci.CrtDerFile = crtDerFile;

                            cp.ExportCertificate(crt, EncodingFormat.PEM, pemTarget);
                            ci.CrtPemFile = crtPemFile;
                        }

                        // Extract a few pieces of info from the issued
                        // cert that we like to have quick access to
                        var x509 = new X509Certificate2(ci.CertificateRequest.GetCertificateContent());
                        ci.SerialNumber       = x509.SerialNumber;
                        ci.Thumbprint         = x509.Thumbprint;
                        ci.SignatureAlgorithm = x509.SignatureAlgorithm?.FriendlyName;
                        ci.Signature          = x509.GetCertHashString();
                    }
                }

                vp.SaveVault(v);

                WriteObject(ci);
            }
        }
Example #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.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)
                    {
                        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)
                    {
                        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);
            }
        }
Example #20
0
        protected override void ProcessRecord()
        {
            var pc = new ProviderConfig
            {
                Id                = EntityHelper.NewId(),
                Alias             = Alias,
                Label             = Label,
                Memo              = Memo,
                DnsProvider       = DnsProvider,
                WebServerProvider = WebServerProvider,
                FilePath          = FilePath
            };

            using (var vp = InitializeVault.GetVaultProvider(VaultProfile))
            {
                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 = ProviderConfigSamples.Loader.LoadDnsProviderConfig(
                        DnsProvider);
                }
                if (!string.IsNullOrEmpty(WebServerProvider))
                {
                    s = ProviderConfigSamples.Loader.LoadWebServerProviderConfig(
                        WebServerProvider);
                }

                var temp = Path.GetTempFileName();
                if (string.IsNullOrWhiteSpace(FilePath))
                {
                    using (var fs = new FileStream(temp, FileMode.Create))
                    {
                        s.CopyTo(fs);
                    }
                    EditFile(temp, EditWith);
                }
                else
                {
                    var config = new ProviderConfigDto
                    {
                        Provider = new Provider
                        {
                            Type     = "ACMESharp.WebServer.ManualWebServerProvider, ACMESharp",
                            FilePath = FilePath
                        }
                    };

                    var output = JsonConvert.SerializeObject(config);

                    s = new MemoryStream(Encoding.UTF8.GetBytes(output));
                    using (var fs = new FileStream(temp, FileMode.Create))
                    {
                        s.CopyTo(fs);
                    }
                }

                var pcAsset = vp.CreateAsset(VaultAssetType.ProviderConfigInfo, $"{pc.Id}.json");
                using (Stream fs = new FileStream(temp, FileMode.Open),
                       assetStream = vp.SaveAsset(pcAsset))
                {
                    fs.CopyTo(assetStream);
                }
                File.Delete(temp);

                s.Close();
                s.Dispose();
            }
        }