public async Task TestStoreCredentialDictionary()
        {
            var secrets = new Dictionary <string, string>();

            secrets.Add("zoneid", "ABC123");
            secrets.Add("secretid", "thereisnosecret");

            var test = new StoredCredential
            {
                ProviderType = "DNS01.API.Route53",
                Title        = "A test credential",
                StorageKey   = Guid.NewGuid().ToString(),
                Secret       = Newtonsoft.Json.JsonConvert.SerializeObject(secrets)
            };

            var credentialsManager = new CredentialsManager();

            credentialsManager.StorageSubfolder = "Tests\\credentials";
            var result = await credentialsManager.UpdateCredential(test);

            Assert.IsNotNull(result, "Credential stored OK");

            var list = await credentialsManager.GetStoredCredentials();

            Assert.IsTrue(list.Any(l => l.StorageKey == test.StorageKey), "Credential retrieved");

            var secret = await credentialsManager.GetUnlockedCredentialsDictionary(test.StorageKey);

            Assert.IsNotNull(secret);
            Assert.IsTrue(secret["zoneid"] == "ABC123", "Credential decrypted");
        }
Beispiel #2
0
        public async Task InitTest()
        {
            var credentialsManager = new CredentialsManager();

            _credentials = await credentialsManager.GetUnlockedCredentialsDictionary(_credStorageKey);

            _provider = new Providers.DNS.Cloudflare.DnsProviderCloudflare(_credentials);
            await _provider.InitProvider();
        }
Beispiel #3
0
        public async Task InitTest()
        {
            var credentialsManager = new CredentialsManager();

            _credentials = await credentialsManager.GetUnlockedCredentialsDictionary(_credStorageKey);

            _provider = new Providers.DNS.Azure.DnsProviderAzure(_credentials);
            await _provider.InitProvider(new Dictionary <string, string> {
            });
        }
Beispiel #4
0
        public async Task TestSftpFileCopy()
        {
            var credentialsManager = new CredentialsManager
            {
                StorageSubfolder = "credentials\\test"
            };

            string destPath = ConfigSettings["TestSSHPath"];

            var storedCred = await credentialsManager.GetUnlockedCredentialsDictionary(ConfigSettings["TestCredentialsKey_SSH"]);

            // var credentials = new UserCredentials(storedCred["username"], storedCred["password"]);

            // create a test temp file
            var tmpPath = Path.GetTempFileName();

            File.WriteAllText(tmpPath, "This is a test temp file");

            var files = new List <FileCopy>
            {
                new FileCopy {
                    SourcePath = tmpPath, DestinationPath = destPath + "/testfilecopy.txt"
                }
            };

            var client = new SftpClient(new SshConnectionConfig
            {
                Host           = ConfigSettings["TestSSHHost"],
                KeyPassphrase  = storedCred["password"],
                Port           = 22,
                Username       = storedCred["username"],
                PrivateKeyPath = ConfigSettings["TestSSHPrivateKeyPath"]
            });

            // test file list
            var fileList = client.ListFiles(destPath, null);

            Assert.IsTrue(fileList.Count > 0);

            // test file copy
            var copiedOK = client.CopyLocalToRemote(files, null);

            Assert.IsTrue(copiedOK);

            File.Delete(tmpPath);
        }
        public async Task TestDeployToKeyVault()
        {
            var deploymentTasks = new List <DeploymentTask>();

            var azureKeyVaultUri = ConfigSettings["Azure_TestKeyVaultUri"];
            var inputFile        = ConfigSettings["TestLocalPath"] + "\\testcert.pfx";

            var tasktypeId = Plugin.DeploymentTasks.Azure.AzureKeyVault.Definition.Id.ToLower();

            var config = new DeploymentTaskConfig
            {
                TaskTypeId        = tasktypeId,
                TaskName          = "A test pfx export task",
                ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL,

                Parameters = new List <ProviderParameterSetting>
                {
                    new ProviderParameterSetting("vault_uri", azureKeyVaultUri)
                }
            };

            var credentialsManager = new CredentialsManager();
            var credentials        = await credentialsManager.GetUnlockedCredentialsDictionary(ConfigSettings["TestCredentialsKey_AzureKeyVault"]);

            var provider = DeploymentTaskProviderFactory.Create(tasktypeId, _pluginManager.DeploymentTaskProviders);

            var t = new DeploymentTask(provider, config, credentials);

            deploymentTasks.Add(t);

            // perform preview deployments
            var managedCert = GetMockManagedCertificate("DeploymentTest", "123", PrimaryTestDomain, PrimaryIISRoot);

            managedCert.CertificatePath = inputFile;

            foreach (var task in deploymentTasks)
            {
                var results = await task.Execute(_log, null, managedCert, CancellationToken.None, new DeploymentContext { }, isPreviewOnly : false);

                // assert new valid pfx exists in destination
                Assert.IsTrue(results.All(r => r.IsSuccess));
            }
        }
Beispiel #6
0
        public async Task TestWindowsNetworkFileCopy()
        {
            var destPath = ConfigSettings["TestUNCPath"];

            var credentialsManager = new CredentialsManager
            {
                StorageSubfolder = "credentials\\test"
            };

            var storedCred = await credentialsManager.GetUnlockedCredentialsDictionary(ConfigSettings["TestCredentialsKey_UNC"]);

            // create a test temp file
            var tmpPath = Path.GetTempFileName();

            File.WriteAllText(tmpPath, "This is a test temp file");
            var files = new List <FileCopy>
            {
                new FileCopy {
                    SourcePath = tmpPath, DestinationPath = destPath + @"\test-copy.txt"
                }
            };

            var credentials = Plugin.DeploymentTasks.Shared.Helpers.GetWindowsCredentials(storedCred);

            var client = new WindowsNetworkFileClient(credentials);

            // test file list
            var fileList = client.ListFiles(destPath);

            Assert.IsTrue(fileList.Count > 0);

            // test file copy
            var results = client.CopyLocalToRemote(_log, files);

            File.Delete(tmpPath);

            Assert.IsTrue(results.All(s => s.IsSuccess == true));
        }
Beispiel #7
0
        public async Task <DnsChallengeHelperResult> GetDnsProvider(string providerTypeId, string credentialsId, Dictionary <string, string> parameters)
        {
            var credentialsManager = new CredentialsManager();
            var credentials        = new Dictionary <string, string>();

            IDnsProvider dnsAPIProvider = null;

            if (!string.IsNullOrEmpty(credentialsId))
            {
                // decode credentials string array
                try
                {
                    credentials = await credentialsManager.GetUnlockedCredentialsDictionary(credentialsId);
                }
                catch (Exception)
                {
                    return(new DnsChallengeHelperResult
                    {
                        Result = new ActionResult {
                            IsSuccess = false, Message = "DNS Challenge API Credentials could not be decrypted. The original user must be used for decryption."
                        },
                        PropagationSeconds = 0,
                        IsAwaitingUser = false
                    });
                }
            }

            try
            {
                dnsAPIProvider = await ChallengeProviders.GetDnsProvider(providerTypeId, credentials, parameters);
            }
            catch (ChallengeProviders.CredentialsRequiredException)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "This DNS Challenge API requires one or more credentials to be specified."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }
            catch (Exception exp)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = $"DNS Challenge API Provider could not be created. Check all required credentials are set and software dependencies installed. {exp.ToString()}"
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }

            if (dnsAPIProvider == null)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "DNS Challenge API Provider not set or could not load."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }

            return(new DnsChallengeHelperResult
            {
                Result = new ActionResult {
                    IsSuccess = true, Message = "Create Provider Instance"
                },
                Provider = dnsAPIProvider
            });
        }
Beispiel #8
0
        public async Task <DnsChallengeHelperResult> CompleteDNSChallenge(ILog log, ManagedCertificate managedcertificate, string domain, string txtRecordName, string txtRecordValue)
        {
            // for a given managed site configuration, attempt to complete the required challenge by
            // creating the required TXT record

            var credentialsManager = new CredentialsManager();
            Dictionary <string, string> credentials = new Dictionary <string, string>();

            IDnsProvider dnsAPIProvider = null;

            var challengeConfig = managedcertificate.GetChallengeConfig(domain);

            /*if (String.IsNullOrEmpty(challengeConfig.ZoneId))
             * {
             *  return new ActionResult { IsSuccess = false, Message = "DNS Challenge Zone Id not set. Set the Zone Id to proceed." };
             * }*/

            if (!String.IsNullOrEmpty(challengeConfig.ChallengeCredentialKey))
            {
                // decode credentials string array
                try
                {
                    credentials = await credentialsManager.GetUnlockedCredentialsDictionary(challengeConfig.ChallengeCredentialKey);
                }
                catch (Exception)
                {
                    return(new DnsChallengeHelperResult
                    {
                        Result = new ActionResult {
                            IsSuccess = false, Message = "DNS Challenge API Credentials could not be decrypted. The original user must be used for decryption."
                        },
                        PropagationSeconds = 0,
                        IsAwaitingUser = false
                    });
                }
            }

            var parameters = new Dictionary <String, string>();

            if (challengeConfig.Parameters != null)
            {
                foreach (var p in challengeConfig.Parameters)
                {
                    parameters.Add(p.Key, p.Value);
                }
            }

            try
            {
                dnsAPIProvider = await ChallengeProviders.GetDnsProvider(challengeConfig.ChallengeProvider, credentials, parameters, log);
            }
            catch (ChallengeProviders.CredentialsRequiredException)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "This DNS Challenge API requires one or more credentials to be specified."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }
            catch (Exception exp)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = $"DNS Challenge API Provider could not be created. Check all required credentials are set. {exp.ToString()}"
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }

            if (dnsAPIProvider == null)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "DNS Challenge API Provider not set or not recognised. Select an API to proceed."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }

            string zoneId = null;

            if (parameters != null && parameters.ContainsKey("zoneid"))
            {
                zoneId = parameters["zoneid"]?.Trim();
            }
            else
            {
                zoneId = challengeConfig.ZoneId?.Trim();
            }

            if (dnsAPIProvider != null)
            {
                //most DNS providers require domains to by ASCII
                txtRecordName = _idnMapping.GetAscii(txtRecordName).ToLower();

                log.Information($"DNS: Creating TXT Record '{txtRecordName}' with value '{txtRecordValue}', in Zone Id '{zoneId}' using API provider '{dnsAPIProvider.ProviderTitle}'");
                try
                {
                    var result = await dnsAPIProvider.CreateRecord(new DnsRecord
                    {
                        RecordType       = "TXT",
                        TargetDomainName = domain,
                        RecordName       = txtRecordName,
                        RecordValue      = txtRecordValue,
                        ZoneId           = zoneId
                    });

                    result.Message = $"{dnsAPIProvider.ProviderTitle} :: {result.Message}";

                    return(new DnsChallengeHelperResult
                    {
                        Result = result,
                        PropagationSeconds = dnsAPIProvider.PropagationDelaySeconds,
                        IsAwaitingUser = challengeConfig.ChallengeProvider.Contains(".Manual")
                    });
                }
                catch (Exception exp)
                {
                    return(new DnsChallengeHelperResult
                    {
                        Result = new ActionResult {
                            IsSuccess = false, Message = $"Failed [{dnsAPIProvider.ProviderTitle}]: " + exp.Message
                        },
                        PropagationSeconds = 0,
                        IsAwaitingUser = false
                    });
                }

                //TODO: DNS query to check for new record

                /*
                 * if (result.IsSuccess)
                 * {
                 *  // do our own txt record query before proceeding with challenge completion
                 *
                 *  int attempts = 3;
                 *  bool recordCheckedOK = false;
                 *  var networkUtil = new NetworkUtils(false);
                 *
                 *  while (attempts > 0 && !recordCheckedOK)
                 *  {
                 *      recordCheckedOK = networkUtil.CheckDNSRecordTXT(domain, txtRecordName, txtRecordValue);
                 *      attempts--;
                 *      if (!recordCheckedOK)
                 *      {
                 *          await Task.Delay(1000); // hold on a sec
                 *      }
                 *  }
                 *
                 * // wait for provider specific propogation delay
                 *
                 * // FIXME: perform validation check in DNS nameservers await
                 * // Task.Delay(dnsAPIProvider.PropagationDelaySeconds * 1000);
                 *
                 * return result;
                 * }
                 * else
                 * {
                 * return result;
                 * }
                 */
            }
            else
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "Error: Could not determine DNS API Provider."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }
        }
Beispiel #9
0
        public async Task <DnsChallengeHelperResult> DeleteDNSChallenge(ILog log, ManagedCertificate managedcertificate, string domain, string txtRecordName)
        {
            // for a given managed site configuration, attempt to delete the TXT record created for
            // the challenge
            var credentialsManager = new CredentialsManager();
            var credentials        = new Dictionary <string, string>();

            IDnsProvider dnsAPIProvider = null;

            var challengeConfig = managedcertificate.GetChallengeConfig(domain);

            if (challengeConfig == null || challengeConfig.ChallengeProvider == null)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = true, Message = $"The DNS record {txtRecordName} can now be removed."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }

            if (challengeConfig.ChallengeProvider.Contains(".Manual"))
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = true, Message = $"The DNS record {txtRecordName} can now be removed."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = true
                });
            }

            if (!String.IsNullOrEmpty(challengeConfig.ChallengeCredentialKey))
            {
                // decode credentials string array
                try
                {
                    credentials = await credentialsManager.GetUnlockedCredentialsDictionary(challengeConfig.ChallengeCredentialKey);
                }
                catch (Exception)
                {
                    return(new DnsChallengeHelperResult
                    {
                        Result = new ActionResult {
                            IsSuccess = false, Message = "DNS Challenge API Credentials could not be decrypted. The original user must be used for decryption."
                        },
                        PropagationSeconds = 0,
                        IsAwaitingUser = false
                    });
                }
            }

            var parameters = new Dictionary <String, string>();

            if (challengeConfig.Parameters != null)
            {
                foreach (var p in challengeConfig.Parameters)
                {
                    parameters.Add(p.Key, p.Value);
                }
            }

            try
            {
                dnsAPIProvider = await ChallengeProviders.GetDnsProvider(challengeConfig.ChallengeProvider, credentials, parameters);
            }
            catch (ChallengeProviders.CredentialsRequiredException)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "This DNS Challenge API requires one or more credentials to be specified."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }
            catch (Exception exp)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = $"DNS Challenge API Provider could not be created. Check all required credentials are set. {exp.ToString()}"
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }

            if (dnsAPIProvider == null)
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "DNS Challenge API Provider not set or not recognised. Select an API to proceed."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }

            string zoneId = null;

            if (parameters != null && parameters.ContainsKey("zoneid"))
            {
                zoneId = parameters["zoneid"]?.Trim();
            }
            else
            {
                zoneId = challengeConfig.ZoneId?.Trim();
            }

            if (dnsAPIProvider != null)
            {
                //most DNS providers require domains to by ASCII
                txtRecordName = _idnMapping.GetAscii(txtRecordName).ToLower();

                log.Information($"DNS: Deleting TXT Record '{txtRecordName}', in Zone Id '{zoneId}' using API provider '{dnsAPIProvider.ProviderTitle}'");
                try
                {
                    var result = await dnsAPIProvider.DeleteRecord(new DnsRecord
                    {
                        RecordType       = "TXT",
                        TargetDomainName = domain,
                        RecordName       = txtRecordName,
                        ZoneId           = zoneId
                    });

                    result.Message = $"{dnsAPIProvider.ProviderTitle} :: {result.Message}";

                    return(new DnsChallengeHelperResult
                    {
                        Result = result,
                        PropagationSeconds = dnsAPIProvider.PropagationDelaySeconds,
                        IsAwaitingUser = challengeConfig.ChallengeProvider.Contains(".Manual")
                    });
                }
                catch (Exception exp)
                {
                    return(new DnsChallengeHelperResult
                    {
                        Result = new ActionResult {
                            IsSuccess = false, Message = $"Failed [{dnsAPIProvider.ProviderTitle}]: " + exp.Message
                        },
                        PropagationSeconds = 0,
                        IsAwaitingUser = false
                    });
                }
            }
            else
            {
                return(new DnsChallengeHelperResult
                {
                    Result = new ActionResult {
                        IsSuccess = false, Message = "Error: Could not determine DNS API Provider."
                    },
                    PropagationSeconds = 0,
                    IsAwaitingUser = false
                });
            }
        }