public PendingAuthorization PerformIISAutomatedChallengeResponse(IISManager iisManager, ManagedSite managedSite, PendingAuthorization pendingAuth) { var requestConfig = managedSite.RequestConfig; var domain = pendingAuth.Identifier.Dns; if (pendingAuth.Challenge != null) { if (pendingAuth.Challenge.ChallengeData is ACMESharp.ACME.HttpChallenge && requestConfig.PerformChallengeFileCopy /* is this needed? */) { var check = PrepareChallengeResponse_Http01(iisManager, domain, managedSite, pendingAuth); if (requestConfig.PerformExtensionlessConfigChecks) { pendingAuth.ExtensionlessConfigCheckedOK = check(); } } if (pendingAuth.Challenge.ChallengeData is ACMESharp.ACME.TlsSniChallenge) { var check = PrepareChallengeResponse_TlsSni01(iisManager, domain, managedSite, pendingAuth); if (requestConfig.PerformTlsSniBindingConfigChecks) { // set config check OK if all checks return true pendingAuth.TlsSniConfigCheckedOK = check(); } } } return(pendingAuth); }
public IISManagerTests() { iisManager = new IISManager(); //perform setup for IIS SetupIIS(); }
private void InitSelectedCertTypeControl() { if (lstRequestType.SelectedIndex == (int)CertControlType.IIS) { if (lstRequestType.SelectedIndex == (int)CertControlType.IIS) { var iisManager = new IISManager(); var version = iisManager.GetIisVersion(); if (version.Major == 0) { //no iis MessageBox.Show("You do not have IIS Installed locally. Automated configuration will be unavailable."); lstRequestType.SelectedIndex = 1; //generic } else { //IIS selected, setup IIS cert request control SetupSelectedCertRequestControl(new CertRequestSettingsIIS()); } } } if (lstRequestType.SelectedIndex == (int)CertControlType.GenericHttp) { SetupSelectedCertRequestControl(new CertRequestHTTPGeneric()); } }
static void Main(string[] args) { string dir = Directory.GetCurrentDirectory(); BasicConfigurator.Configure(); if (Assembly.GetExecutingAssembly().GetCustomAttributes(false).OfType <DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled)) { //Returns the static path for debugging purposes. dir = "C:\\Users\\JOTIS\\source\\repos\\IISSetup"; } Settings settings = new Settings(); var builder = new ConfigurationBuilder() .SetBasePath(dir) .AddJsonFile("App_Data/appsettings.json", optional: false, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); configuration.GetSection("AppSettings").Bind(settings); WindowsIdentity user = WindowsIdentity.GetCurrent(); if (user.IsGuest || user.IsAnonymous) { Console.WriteLine("User is currently an ninvalid user...."); Environment.Exit(-1); } foreach (var application in settings.Applications) { IISManager manager = new IISManager(application); manager.CreateInstance(); } }
public CertRequestTests() { certifyManager = new CertifyManager(); iisManager = new IISManager(); //perform setup for IIS SetupIIS(); }
public JsonResult GetIISInfo() { return(Json(new { Sites = IISManager.GetSites(), W3wps = IISManager.GetWorkerProcesses() })); }
public static void Init() { iiscontrol = new IISManager(); iiscontrol.Connect(); GetFirstFolder(); GetSecondFolder(); ReadConfig(); ReadDiskInfo(); if (MessageQueue.Exists(FileSyncMQ)) { q = new MessageQueue(FileSyncMQ); } else { q = MessageQueue.Create(FileSyncMQ,true); q.SetPermissions("Everyone", System.Messaging.MessageQueueAccessRights.FullControl); } }
/// <summary> /// Tears down. /// </summary> public void TearDown() { if (TestConfig.UseTestMailServer) { // Stop Mail Server this.SmtpServer?.Stop(); } if (TestConfig.UseExistingInstallation) { return; } var applicationPath = Path.Combine(TestConfig.InstallPhysicalPath, TestConfig.TestApplicationName); // Recycle App Pool IISManager.RecycleApplicationPool(TestConfig.TestApplicationName); // Delete App from IIS IISManager.DeleteIISApplication(TestConfig.TestApplicationName); // Detach Database DBManager.DropDatabase(TestConfig.TestDatabase); // Delete Files if (File.Exists(Path.Combine(TestConfig.InstallPhysicalPath, "YAF-BIN.zip"))) { File.Delete(Path.Combine(TestConfig.InstallPhysicalPath, "YAF-BIN.zip")); } Directory.Delete(applicationPath, true); this.ChromeDriver.Close(); }
public void CreateIISSite_SiteInfo_Success() { IISManager.CreateIISSite("E:\\PublishOutput\\*", new Site { Name = "PowerShellSite", Port = 805, PhysicalPath = "E:\\03_ReleaseWebSite\\PowerShellSite", DefaultPage = "http://localhost:805/home/windowsSignalrTest" }, true); }
public async Task <JsonResult> StopSite(int siteId) { if (IISManager.StopSite(siteId)) { await YummyOnlineManager.RecordLog(Log.LogProgram.System, Log.LogLevel.Warning, $"Site {IISManager.GetSiteById(siteId).Name} Stoped"); return(Json(new JsonSuccess())); } return(Json(new JsonError("无法停止"))); }
private void PopulateManagedSiteSettings(string siteId) { ValidationError = null; var managedSite = SelectedItem; managedSite.Name = SelectedWebSite.SiteName; //TODO: if this site would be a duplicate need to increment the site name //set defaults first managedSite.RequestConfig.PerformExtensionlessConfigChecks = true; managedSite.RequestConfig.PerformChallengeFileCopy = true; managedSite.RequestConfig.PerformAutomatedCertBinding = true; managedSite.RequestConfig.PerformAutoConfig = true; managedSite.RequestConfig.EnableFailureNotifications = true; managedSite.RequestConfig.ChallengeType = "http-01"; managedSite.IncludeInAutoRenew = true; managedSite.DomainOptions = new List <DomainOption>(); //for the given selected web site, allow the user to choose which domains to combine into one certificate var allSites = new IISManager().GetSiteBindingList(false, siteId); var domains = new List <DomainOption>(); foreach (var d in allSites) { if (d.SiteId == siteId) { DomainOption opt = new DomainOption { Domain = d.Host, IsPrimaryDomain = false, IsSelected = true }; domains.Add(opt); } } if (domains.Any()) { //mark first domain as primary, if we have no other settings if (!domains.Any(d => d.IsPrimaryDomain == true)) { domains[0].IsPrimaryDomain = true; } managedSite.DomainOptions = domains; //MainViewModel.EnsureNotifyPropertyChange(nameof(MainViewModel.PrimarySubjectDomain)); } else { //TODO: command to show error in UI ValidationError = "The selected site has no domain bindings setup. Configure the domains first using Edit Bindings in IIS."; } //TODO: load settings from previously saved managed site? RaisePropertyChanged(nameof(PrimarySubjectDomain)); }
static IISActions() { if (IsIIS7Upwards) { iisManager = new IIS7UpwardsManager(); } else { iisManager = new IIS6Manager(); } }
public void Update_sites_removing_site() { var contosoWebSite = new WebSite { Name = ContosoWebSiteName, Bindings = new List <Binding> { new Binding { Protocol = "http", IpAddress = "127.0.0.1", Port = 8081, HostName = "contoso.com" } } }; var fabrikamWebSite = new WebSite { Name = FabrikamWebSiteName, Bindings = new List <Binding> { new Binding { Protocol = "https", IpAddress = "127.0.0.1", Port = 8443, CertificateThumbprint = "12345" } } }; var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount); var iisManager = new IISManager(LocalSitesPath, TempSitesPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug); var sites = new List <WebSite> { contosoWebSite, fabrikamWebSite }; iisManager.UpdateSites(sites, _excludedSites); Assert.AreEqual(2, RetrieveWebSites().Count() - _excludedSites.Count); sites.RemoveAt(0); iisManager.UpdateSites(sites, _excludedSites); // Asserts Assert.AreEqual(1, RetrieveWebSites().Count() - _excludedSites.Count); Site contoso = RetrieveWebSite(ContosoWebSiteName); Site fabrikam = RetrieveWebSite(FabrikamWebSiteName); Assert.IsNull(contoso); Assert.IsNotNull(fabrikam); }
static IISActions() { if (IsIIS7Upwards) { iisManager = new IIS7UpwardsManager(); } else { iisManager = new IIS6Manager(); } }
public void GivenIHaveCreatedASiteInIISWithTheAlias(string appPool, string portalAlias) { string physicalPath = Directory.GetCurrentDirectory(); physicalPath = physicalPath.Replace("\\Tests\\Fixtures", "\\Website"); if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DefaultPhysicalAppPath"])) { physicalPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"]; } IISManager.CreateIISApplication(portalAlias, physicalPath); IISManager.SetApplicationPool(portalAlias, appPool); }
public PendingAuthorization PerformIISAutomatedChallengeResponse(IISManager iisManager, ManagedSite managedSite, PendingAuthorization pendingAuth) { var processedAuth = _vaultManager.PerformIISAutomatedChallengeResponse(iisManager, managedSite, pendingAuth); if (_vaultManager.ActionLogs != null) { processedAuth.LogItems = new List <string>(); foreach (var a in _vaultManager.ActionLogs) { processedAuth.LogItems.Add(a.Command + (a.Result != null ? a.Result : "")); } } return(processedAuth); }
public PendingAuthorization PerformIISAutomatedChallengeResponse(IISManager iisManager, ManagedSite managedSite, PendingAuthorization pendingAuth) { var processedAuth = _vaultManager.PerformIISAutomatedChallengeResponse(iisManager, managedSite, pendingAuth); /*// FIXME: vault logs need to be filtered by managed site * if (_vaultManager.ActionLogs != null) * { * processedAuth.LogItems = new List<string>(); * foreach (var a in _vaultManager.ActionLogs) * { * processedAuth.LogItems.Add(a.Command + (a.Result != null ? a.Result : "")); * } * }*/ return(processedAuth); }
private void startwechat(HttpContext context) { try { var config = new SiteConfig(); if (WebUtil.GetContextPath().Contains(config.SITE_URL)) { string VirName = WebUtil.GetVirName(); int SiteNumber = int.Parse(config.Wechat_SiteNumber); string ZipPath = config.Wechat_ZipPath; string SitePath = config.Wechat_SitePath; Utility.Tools.UnZipFile(ZipPath, SitePath, VirName); bool sitestatus = IISManager.CreateWebSite(string.Empty, VirName, SitePath + VirName + @"\weixin", false, 1, SiteNumber, "localhost"); string ConfigPath = SitePath + VirName + @"\weixin\Web.config"; Dictionary <string, object> dic = new Dictionary <string, object>(); string SiteURL = config.SITE_URL; if (SiteURL.EndsWith("/")) { SiteURL = SiteURL.Substring(0, SiteURL.Length - 1); } if (!SiteURL.EndsWith(VirName) && !VirName.Equals("saas")) { SiteURL = SiteURL + "/" + VirName; } dic["apiurl"] = SiteURL + "/handler/api.ashx"; dic["SITE_URL"] = SiteURL; Utility.IISManager.UpdateConfigValue(ConfigPath, dic); } var list = Foresight.DataAccess.SysConfig.GetSysConfigListByType("Wechat"); var data = list.FirstOrDefault(p => p.Name.Equals("WechatEnable")); if (data == null) { data = new Foresight.DataAccess.SysConfig(); data.AddTime = DateTime.Now; data.ConfigType = "Wechat"; } data.Name = "WechatEnable"; data.Value = "1"; data.Save(); WebUtil.WriteJsonResult(context, "生成成功"); } catch (Exception ex) { LogHelper.WriteError("WechatSetup", "startwechat", ex); WebUtil.WriteJsonError(context, ErrorCode.InvalideRequest, ex); } }
private void PopulateWebsitesFromIIS() { var iisManager = new IISManager(); var siteList = iisManager.GetSiteList(); this.lstSites.Items.Clear(); this.lstSites.DisplayMember = "Description"; foreach (var s in siteList) { this.lstSites.Items.Add(s); } if (lstSites.Items.Count > 0) { this.lstSites.SelectedIndex = 0; RefreshSelectedWebsite(); } }
private void btnLockdown_Click(object sender, EventArgs e) { var prompt = MessageBox.Show("This will create/update system-wide registry keys disabling some known insecure SSL protocols and ciphers. Do you wish to continue?", Properties.Resources.AppName, MessageBoxButtons.YesNo); if (prompt == DialogResult.Yes) { var iisManager = new IISManager(); try { iisManager.PerformSSLProtocolLockdown(); MessageBox.Show("Registry changes applied. You should restart this machine for changes to take effect."); } catch (Exception) { MessageBox.Show("Sorry, the registry changes failed to apply. You may not have the required permissions."); } } }
/// <summary> /// 尝试创建升级中转站 /// </summary> public void TryCreateUpgradeTransferSite(Site siteInfo) { try { if (siteInfo == null) { throw new ArgumentNullException("siteinfo is null"); } var rootPath = AppDomain.CurrentDomain.BaseDirectory; siteInfo.PhysicalPath = $"{rootPath}" + siteInfo.PhysicalPath; IISManager.CreateSite(siteInfo); Clients.All.tranfersitecallback(new { success = true, msg = "站点创建成功", url = siteInfo.DefaultPage }); } catch (Exception ex) { Logger.Error(ex.Message, ex); Clients.All.tranfersitecallback(new { success = false, msg = ex.Message }); } }
/// <summary> /// Prepares IIS to respond to a tls-sni-01 challenge /// </summary> /// <returns> /// A Boolean-returning Func. Invoke the Func to test the challenge response locally. /// </returns> private Func <bool> PrepareChallengeResponse_TlsSni01(IISManager iisManager, string domain, ManagedSite managedSite, PendingAuthorization pendingAuth) { var requestConfig = managedSite.RequestConfig; var tlsSniChallenge = (ACMESharp.ACME.TlsSniChallenge)pendingAuth.Challenge.ChallengeData; var tlsSniAnswer = (ACMESharp.ACME.TlsSniChallengeAnswer)tlsSniChallenge.Answer; var sha256 = System.Security.Cryptography.SHA256.Create(); var z = new byte[tlsSniChallenge.IterationCount][]; // compute n sha256 hashes, where n=challengedata.iterationcount z[0] = sha256.ComputeHash(Encoding.UTF8.GetBytes(tlsSniAnswer.KeyAuthorization)); for (int i = 1; i < z.Length; i++) { z[i] = sha256.ComputeHash(z[i - 1]); } // generate certs and install iis bindings var cleanupQueue = new List <Action>(); var checkQueue = new List <Func <bool> >(); foreach (string hex in z.Select(b => BitConverter.ToString(b).Replace("-", "").ToLower())) { string sni = $"{hex.Substring(0, 32)}.{hex.Substring(32)}.acme.invalid"; this.LogAction($"Preparing binding at: https://{domain}, sni: {sni}"); var x509 = CertificateManager.GenerateTlsSni01Certificate(sni); CertificateManager.StoreCertificate(x509); iisManager.InstallCertificateforBinding(managedSite, x509, sni); // add check to the queue checkQueue.Add(() => NetUtil.CheckSNI(domain, sni)); // add cleanup actions to queue cleanupQueue.Add(() => iisManager.RemoveHttpsBinding(managedSite, sni)); cleanupQueue.Add(() => CertificateManager.RemoveCertificate(x509)); } // configure cleanup to execute the cleanup queue pendingAuth.Cleanup = () => cleanupQueue.ForEach(a => a()); // perform our own config checks pendingAuth.TlsSniConfigCheckedOK = true; return(() => checkQueue.All(check => check())); }
public void Rollback_Website_with_VDIR_Test() { var client = GetClient(); const string version1 = "1.3.3.7"; const string version2 = "1.3.3.8"; var request = new TriggerDeployment() { AppPoolName = "ZZZ_Integration_PoolName", AppPoolUser = "******", AppPoolPassword = "******", WebsiteName = "ZZZ_Integration_Website_VDIR", AppRoot = "/sub1/sub2", PackageId = "IntegrationTest", PackageVersion = version1, WebsitePhysicalPath = @"C:\temp\www", WebsitePort = 8000, RuntimeVersion = RuntimeVersion.Version40, AppName = "App", AppPhysicalPath = @"c:\temp\int-app", }; client.PostFileWithRequest <TriggerDeploymentResponse>("/deployments", new FileInfo("src/PowerDeploy.IISDeployService.Tests/Files/package.zip".MapVcsRoot()), request).PrintDump(); request.PackageVersion = version2; client.PostFileWithRequest <TriggerDeploymentResponse>("/deployments", new FileInfo("src/PowerDeploy.IISDeployService.Tests/Files/package.zip".MapVcsRoot()), request).PrintDump(); var rollbackRequest = new RollbackDeployment() { WebsiteName = request.WebsiteName, RollbackTarget = "{0}_v{1}".Fmt(request.PackageId, version1), AppName = request.AppName, AppRoot = request.AppRoot, }; client.Post(rollbackRequest); var actual = new IISManager().GetApplicationPath(request.WebsiteName, request.AppRoot, request.AppName); Assert.AreEqual(@"{0}\{1}_v{2}".Fmt(request.AppPhysicalPath, request.PackageId, version1), actual); }
public static void Main(string[] args) { _log.Info("Started"); try { var userManager = new UserManager(); var copyManager = new CopyManager(); var iisManagement = new IISManager(_webServerConfig, userManager, copyManager); iisManagement.CreateUserSite(); /// } catch (Exception ex) { _log.Error(ex.Message); } _log.Info("Finished"); Console.ReadKey(); }
public WebSocketServer(string ip, int port, Action <string, Log.LogLevel> logDelegate) { GetPhysicallyInstalledSystemMemory(out memorySize); FleckLog.Level = LogLevel.Error + 1; Fleck.WebSocketServer server = new Fleck.WebSocketServer($"ws://{ip}:{port}"); this.logDelegate = logDelegate; server.Start(serverConnected); try { IISManager.GetSites().ForEach(info => { siteCurrentConnections.Add(new PerformanceCounter("Web Service", "Current Connections", info.Name)); }); } catch { } Timer timer = new Timer(1000); timer.Elapsed += Timer_Elapsed; timer.Start(); }
private void btnApply_Click(object sender, EventArgs e) { //attempt to match iis site with cert domain, auto create mappinngs var ident = parentApp.VaultManager.GetIdentifier(item.IdentifierRef.ToString()); if (ident != null) { string certFolderPath = parentApp.VaultManager.GetCertificateFilePath(item.Id, LocalDiskVault.ASSET); string pfxFile = item.Id.ToString() + "-all.pfx"; string pfxPath = Path.Combine(certFolderPath, pfxFile); IISManager iisManager = new IISManager(); if (iisManager.InstallCertForDomain(ident.Dns, pfxPath, cleanupCertStore: true, skipBindings: false)) { //all done MessageBox.Show("Certificate installed and SSL bindings updated for " + ident.Dns); return; } } MessageBox.Show("Could not match cert identifier to site."); }
internal void ListManagedSites() { var siteManager = new ItemManager(); siteManager.LoadSettings(); var managedSites = siteManager.GetManagedSites(); IISManager iisManager = new IISManager(); foreach (var site in managedSites) { var siteIISInfo = iisManager.GetSiteById(site.GroupId); string status = "Running"; if (!iisManager.IsSiteRunning(site.GroupId)) { status = "Not Running"; } Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"{site.Name},{status},{site.DateExpiry}"); } }
public PendingAuthorization PerformIISAutomatedChallengeResponse(IISManager iisManager, ManagedSite managedSite, PendingAuthorization pendingAuth) { var requestConfig = managedSite.RequestConfig; bool extensionlessConfigOK = false; //if validation proxy enabled, access to the domain being validated is checked via our remote API rather than directly on the servers bool checkViaProxy = Certify.Properties.Settings.Default.EnableValidationProxyAPI; //if copying the file for the user, attempt that now if (pendingAuth.Challenge != null && requestConfig.PerformChallengeFileCopy) { var httpChallenge = (ACMESharp.ACME.HttpChallenge)pendingAuth.Challenge.ChallengeData; this.LogAction("Preparing challenge response for LetsEncrypt server to check at: " + httpChallenge.FileUrl); this.LogAction("If the challenge response file is not accessible at this exact URL the validation will fail and a certificate will not be issued."); // get website root path string websiteRootPath = requestConfig.WebsiteRootPath; Environment.SetEnvironmentVariable("websiteroot", iisManager.GetSitePhysicalPath(managedSite)); // sets env variable for this process only websiteRootPath = Environment.ExpandEnvironmentVariables(websiteRootPath); // expand all env variables //copy temp file to path challenge expects in web folder var destFile = Path.Combine(websiteRootPath, httpChallenge.FilePath); var destPath = Path.GetDirectoryName(destFile); if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } //copy challenge response to web folder /.well-known/acme-challenge System.IO.File.WriteAllText(destFile, httpChallenge.FileContent); var wellknownContentPath = httpChallenge.FilePath.Substring(0, httpChallenge.FilePath.LastIndexOf("/")); var testFilePath = Path.Combine(websiteRootPath, wellknownContentPath + "//configcheck"); // write the config check file if it doesn't already exist if (!File.Exists(testFilePath)) { System.IO.File.WriteAllText(testFilePath, "Extensionless File Config Test - OK"); } //create a web.config for extensionless files, then test it (make a request for the extensionless configcheck file over http) string webConfigContent = Core.Properties.Resources.IISWebConfig; if (!File.Exists(destPath + "\\web.config")) { //no existing config, attempt auto config and perform test System.IO.File.WriteAllText(destPath + "\\web.config", webConfigContent); if (requestConfig.PerformExtensionlessConfigChecks) { if (CheckURL("http://" + requestConfig.PrimaryDomain + "/" + wellknownContentPath + "/configcheck", checkViaProxy)) { extensionlessConfigOK = true; } } } else { //web config already exists, don't overwrite it, just test it if (requestConfig.PerformExtensionlessConfigChecks) { if (CheckURL("http://" + requestConfig.PrimaryDomain + "/" + wellknownContentPath + "/configcheck", checkViaProxy)) { extensionlessConfigOK = true; } if (!extensionlessConfigOK && requestConfig.PerformAutoConfig) { //didn't work, try our default config System.IO.File.WriteAllText(destPath + "\\web.config", webConfigContent); if (CheckURL("http://" + requestConfig.PrimaryDomain + "/" + wellknownContentPath + "/configcheck", checkViaProxy)) { extensionlessConfigOK = true; } } } } if (requestConfig.PerformExtensionlessConfigChecks) { if (!extensionlessConfigOK && requestConfig.PerformAutoConfig) { //if first attempt(s) at config failed, try an alternative config webConfigContent = Properties.Resources.IISWebConfigAlt; System.IO.File.WriteAllText(destPath + "\\web.config", webConfigContent); if (CheckURL("http://" + requestConfig.PrimaryDomain + "/" + wellknownContentPath + "/configcheck", checkViaProxy)) { //ready to complete challenge extensionlessConfigOK = true; } } } } //configuration applied, ready to ask LE to validate our answer pendingAuth.ExtensionlessConfigCheckedOK = extensionlessConfigOK; return(pendingAuth); }
public void Rollback_Website_with_VDIR_Test() { var client = GetClient(); const string version1 = "1.3.3.7"; const string version2 = "1.3.3.8"; var request = new TriggerDeployment() { AppPoolName = "ZZZ_Integration_PoolName", AppPoolUser = "******", AppPoolPassword = "******", WebsiteName = "ZZZ_Integration_Website_VDIR", AppRoot = "/sub1/sub2", PackageId = "IntegrationTest", PackageVersion = version1, WebsitePhysicalPath = @"C:\temp\www", WebsitePort = 8000, RuntimeVersion = RuntimeVersion.Version40, AppName = "App", AppPhysicalPath = @"c:\temp\int-app", }; client.PostFileWithRequest<TriggerDeploymentResponse>("/deployments", new FileInfo("src/PowerDeploy.IISDeployService.Tests/Files/package.zip".MapVcsRoot()), request).PrintDump(); request.PackageVersion = version2; client.PostFileWithRequest<TriggerDeploymentResponse>("/deployments", new FileInfo("src/PowerDeploy.IISDeployService.Tests/Files/package.zip".MapVcsRoot()), request).PrintDump(); var rollbackRequest = new RollbackDeployment() { WebsiteName = request.WebsiteName, RollbackTarget = "{0}_v{1}".Fmt(request.PackageId, version1), AppName = request.AppName, AppRoot = request.AppRoot, }; client.Post(rollbackRequest); var actual = new IISManager().GetApplicationPath(request.WebsiteName, request.AppRoot, request.AppName); Assert.AreEqual(@"{0}\{1}_v{2}".Fmt(request.AppPhysicalPath, request.PackageId, version1), actual); }
public PendingAuthorization PerformIISAutomatedChallengeResponse(IISManager iisManager, ManagedSite managedSite, PendingAuthorization pendingAuth) { throw new NotImplementedException(); }
public static void Hello() { var assembly = System.Reflection.Assembly.GetExecutingAssembly(); var curVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("Утилита для мониторинга состояния приложений. Версия: {0}", curVersion); Console.ResetColor(); var products = IISManager.GetProducts().ToArray(); if (products.Length > 0) { Console.WriteLine("Найдены следующие приложения DIRECTUM:"); for (var i = 0; i < products.Length; i++) { Console.WriteLine(" {0}: {1}", i, products[i]); } Console.WriteLine("\nЧтобы запустить быстрое формирование отчета по продукту воспользуйтесь командой 'start'"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("{0} start /a:\"{1}\"", Path.GetFileName(assembly.Location), products.First()); Console.ResetColor(); } var configurations = ConfigurationManager.GetAll().ToArray(); if (configurations.Length > 0) { Console.WriteLine("\nТак же можно использовать существующие конфигурации:"); foreach (var configuration in configurations) { Console.WriteLine(" {0}: {1}", configuration.Name, configuration.Description); } Console.WriteLine("\nЧтобы запустить формирование отчета воспользуйтесь 'start'"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("{0} start /c:\"{1}\"", Path.GetFileName(assembly.Location), configurations.First().Name); Console.ResetColor(); } else { var templates = TemplateManager.GetAll().ToArray(); Console.WriteLine("\nЧтобы создать конфигурацию по продукту воспользуйтесь командой 'create'"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("{0} create /t:\"{1}\"", Path.GetFileName(assembly.Location), templates.First().Name); Console.ResetColor(); Console.WriteLine("Доступны следующие шаблоны:"); foreach (var template in templates) { Console.WriteLine(" {0}: {1}", template.Name, template.Description); } } Console.WriteLine("\nДля уточнения других параметров запуска и команд воспользуйтесь командой 'help'"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("{0} help", Path.GetFileName(assembly.Location)); Console.ResetColor(); }
private void btnRequestCertificate_Click(object sender, EventArgs e) { if (lstSites.SelectedItem == null) { MessageBox.Show("No IIS Site Selected"); return; } if (VaultManager == null) { MessageBox.Show("Vault Manager is null. Please report this problem."); } //prevent further clicks on request button btnRequestCertificate.Enabled = false; ShowProgressBar(); this.Cursor = Cursors.WaitCursor; bool certsApproved = false; bool certsStored = false; CertRequestConfig config = new CertRequestConfig(); var selectItem = (SiteListItem)lstSites.SelectedItem; config.Domain = selectItem.Host; config.PerformChallengeFileCopy = true; config.WebsiteRootPath = Environment.ExpandEnvironmentVariables(selectItem.PhysicalPath); var vaultConfig = VaultManager.GetVaultConfig(); //check if domain already has an associated identifier var identifierAlias = VaultManager.ComputeIdentifierAlias(config.Domain); //try alias or DNS name before creating a new identifier var identifier = VaultManager.GetIdentifier(identifierAlias); if (identifier == null) { identifier = VaultManager.GetIdentifier(config.Domain); } if (identifier != null) { //domain already exists in vault //check if has pending authorization challenges if (identifier.Authorization != null && identifier.Authorization.Challenges != null) { var challenge = identifier.Authorization.Challenges.FirstOrDefault(c => c.Type == "http-01"); if (challenge != null) { if (challenge.Status != "invalid") { //update challenge status MessageBox.Show("An existing challenge was already in progress, status will now be updated. " + challenge.Token); VaultManager.UpdateIdentifierStatus(identifierAlias); identifier = VaultManager.GetIdentifier(identifierAlias , true); challenge = identifier.Authorization.Challenges.FirstOrDefault(c => c.Type == "http-01"); if (challenge.Status == "valid") { certsApproved = true; } } else { MessageBox.Show("The existing challenge for this identifier failed. We will need to create a new one."); identifierAlias += "_" + Guid.NewGuid().ToString().Substring(0, 6); } } } } if (!certsApproved) { var authorization = VaultManager.DomainInitAndRegistration(config, identifierAlias); if (authorization != null) { if (!authorization.ExtensionlessConfigCheckedOK) { MessageBox.Show("Automated checks for extensionless content failed. Authorisations will not be able to complete. Change the web.config in <your site>\\.well-known\\acme-challenge and ensure you can browse to http://<your site>/.well-known/acme-challenge/configcheck before proceeding."); return; } //at this point we can either get the user to manually copy the file to web site folder structure //if file has already been copied we can go ahead and ask the server to verify it //ask server to check our challenge answer is present and correct VaultManager.SubmitChallenge(authorization.Identifier.Alias); //give LE time to check our challenge answer stored on our server Thread.Sleep(2000); VaultManager.UpdateIdentifierStatus(authorization.Identifier.Alias); VaultManager.ReloadVaultConfig(); //check status of the challenge var updatedIdentifier = VaultManager.GetIdentifier(authorization.Identifier.Alias); var challenge = updatedIdentifier.Authorization.Challenges.FirstOrDefault(c => c.Type == "http-01"); //if all OK, we will be ready to fetch our certificate if (challenge?.Status == "valid") { certsApproved = true; } else { if (challenge != null) { MessageBox.Show("Challenge not yet completed. Check that http://" + config.Domain + "/" + challenge.ToString() + " path/file is present and accessible in your web browser."); } else { if (challenge.Status == "invalid") { MessageBox.Show("Challenge failed to complete. Check that http://" + config.Domain + "/" + challenge.ToString() + " path/file is present and accessible in your web browser. You may require extensionless file type mappings"); } } } } else { MessageBox.Show("Could not begin authorization. Check Logs. Ensure the domain being authorized is whitelisted with LetsEncrypt service."); } } //create certs for current authorization string certRef = null; //if (certsApproved) { certRef = VaultManager.CreateCertificate(identifierAlias); VaultManager.UpdateIdentifierStatus(identifierAlias); identifier = VaultManager.GetIdentifier(identifierAlias, true); VaultManager.ReloadVaultConfig(); if (VaultManager.CertExists(identifierAlias)) { certsStored = true; } } //auto setup/install var certInfo = VaultManager.GetCertificate(certRef); if (certInfo != null && certInfo.CrtDerFile == null) { //failed to get cert first time, try again certRef = VaultManager.CreateCertificate(identifierAlias); VaultManager.UpdateIdentifierStatus(identifierAlias); certInfo = VaultManager.GetCertificate(certRef); } //txtOutput.Text = "To complete this request copy the file " + CurrentAuthorization.TempFilePath + " to the following location under your website root (note: no file extension): " + CurrentAuthorization.Challenge.ChallengeAnswer.Key; //ReloadVault(); this.Cursor = Cursors.Default; if (!certsStored) { if (certsApproved) { MessageBox.Show("Certificates approved but not yet stored in vault. Try again later."); CloseParentForm(); return; } else { MessageBox.Show("Certificates not approved yet. Authorization challenge may have failed. Try again later."); CloseParentForm(); return; } } else { if (certInfo != null) { string certFolderPath = VaultManager.GetCertificateFilePath(certInfo.Id, LocalDiskVault.ASSET); string pfxFile = certInfo.Id.ToString() + "-all.pfx"; string pfxPath = Path.Combine(certFolderPath, pfxFile); if (!System.IO.Directory.Exists(certFolderPath)) { System.IO.Directory.CreateDirectory(certFolderPath); } if (!File.Exists(pfxPath)) { //hmm, no pfx, try to create pfx again TODO: shouldn't need this VaultManager.ExportCertificate("=" + certInfo.Id.ToString(), pfxOnly: true); } if (File.Exists(pfxPath)) { //VaultManager.UpdateIdentifierStatus(certInfo.IdentifierRef); //identifier = VaultManager.GetIdentifier(certInfo.IdentifierRef, true); IISManager iisManager = new IISManager(); if (identifier == null || identifier.Dns == null) { MessageBox.Show("Error: identifier/dns is null. Cannot match domain for binding"); } else { if (iisManager.InstallCertForDomain(identifier.Dns, pfxPath, cleanupCertStore: true, skipBindings: !chkAutoBindings.Checked)) { //all done MessageBox.Show("Certificate installed and SSL bindings updated for " + identifier.Dns, Properties.Resources.AppName); CloseParentForm(); return; } if (chkAutoBindings.Checked) { //auto store and create site bindings MessageBox.Show("Your certificate has been imported and SSL bindings updated for " + config.Domain, Properties.Resources.AppName); CloseParentForm(); return; } else { //auto store cert MessageBox.Show("Your certificate has been imported and is ready for you to configure IIS bindings.", Properties.Resources.AppName); CloseParentForm(); return; } } } else { MessageBox.Show("Failed to generate PFX file for Certificate.", Properties.Resources.AppName); CloseParentForm(); return; } } else { //cert was null MessageBox.Show("Certification was not successful. Certificate not valid or not yet authorized.", Properties.Resources.AppName); CloseParentForm(); return; } } }
public static void Start( [Description("Имя приложения для запуска анализа")] string application, [Description("Путь к файлам лога приложения")] string logPath, [DefaultValue("All")] [Description("Наименование конфигурации. По умолчанию обрабатываются все")] string[] config, [DefaultValue(DatePeriod.LastDay)] [Description("Предопределенный период обработки. По умолчанию обработка выполняется за прошлый день")] DatePeriod period, [Description("Дата начала обработки в формате \"yyyy-MM-dd\" или \"yyyy-MM-dd HH:mm:ss\"")] DateTime fromDate, [Description("Дата конца обработки в формате \"yyyy-MM-dd\" или \"yyyy-MM-dd HH:mm:ss\"")] DateTime toDate ) { //TODO: Разбить на методы!!! // Анализ по логам if (!string.IsNullOrEmpty(logPath)) { Configurations.Configuration configuration; foreach (var template in TemplateManager.GetAll().Where(t => !string.IsNullOrEmpty(t.PathModeMask))) { var files = Directory.GetFiles(logPath, template.PathModeMask); if (files.Length > 0) { var dates = files.Select(f => Utility.ExtractDateTime(f)).OrderBy(f => f); if (fromDate == DateTime.MinValue) { fromDate = dates.FirstOrDefault(); } if (toDate == DateTime.MinValue) { toDate = dates.LastOrDefault(); } FillPeriod(period, ref fromDate, ref toDate); configuration = ConfigurationManager.CreateInstant(template, logPath); configuration.Run(fromDate, toDate); } } return; } // Анализ по приложению if (!string.IsNullOrEmpty(application)) { var product = IISManager.GetProducts().FirstOrDefault(a => a.ToString().Equals(application, StringComparison.OrdinalIgnoreCase)); if (product == null) { Core.Application.Log(LogLevel.Error, "Приложение '{0}' не найдено.", application); return; } var configuration = ConfigurationManager.CreateInstant(product); //Заполнение дат, при указании предопределенного периода FillPeriod(period, ref fromDate, ref toDate); configuration.Run(fromDate, toDate); return; } if (config.Contains("All")) { config = Directory.GetDirectories("Configurations").Select(x => Path.GetFileName(x)).ToArray(); } //Заполнение дат, при указании предопределенного периода FillPeriod(period, ref fromDate, ref toDate); foreach (var name in config) { try { Core.Application.Log(LogLevel.Informational, "Запуск обработки '{0}' c {1} до {2}, period {3}", name, fromDate, toDate, period); var configuration = ConfigurationManager.Get(name); if (configuration == null) { Core.Application.Log(LogLevel.Error, "Конфигурация '{0}' отсутствует.", name); Configurations(); return; } configuration.Run(fromDate, toDate); //Core.Configuration(configName).Run() } catch (OperationCanceledException) { Core.Application.Log(LogLevel.Informational, "Вызвано завершение обработки конфигурации {0}", name); } catch (Exception ex) { Core.Application.Log(LogLevel.Error, "Во время обработки конфигурации '{0}' возникла ошибка: {1}", name, ex.Message); while (ex.InnerException != null) { ex = ex.InnerException; Core.Application.Log(LogLevel.Error, "\t --> {0}", ex.Message); } } } }