Example #1
0
        public void TestIisExpressReadOnly()
        {
            var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Environment.SetEnvironmentVariable("JEXUS_TEST_HOME", directoryName);

            if (directoryName == null)
            {
                return;
            }

            string Current  = Path.Combine(directoryName, @"applicationHost.config");
            string Original = Path.Combine(directoryName, @"original2.config");

            TestHelper.CopySiteConfig(directoryName, "original.config");
            File.Copy(Original, Current, true);
            TestHelper.FixPhysicalPathMono(Current);

            var message =
                "The configuration object is read only, because it has been committed by a call to ServerManager.CommitChanges(). If write access is required, use ServerManager to get a new reference.";

#if IIS
            var server = new ServerManager(true, Current);
#else
            var server = new IisExpressServerManager(true, Current);
#endif
            var exception1 = Assert.Throws <InvalidOperationException>(
                () =>
            {
                TestCases.TestIisExpress(server);
            });
            Assert.Equal(message, exception1.Message);

            // site config "Website1"
            var config = server.Sites[0].Applications[0].GetWebConfiguration();

            // enable Windows authentication
            var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
            Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
            Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
            Assert.Equal(true, windowsSection.IsLocked);
            Assert.Equal(false, windowsSection.IsLocallyStored);

            var windowsEnabled = (bool)windowsSection["enabled"];
            Assert.False(windowsEnabled);

            var compression = config.GetSection("system.webServer/urlCompression");
            Assert.Equal(OverrideMode.Inherit, compression.OverrideMode);
            Assert.Equal(OverrideMode.Allow, compression.OverrideModeEffective);
            Assert.Equal(false, compression.IsLocked);
            Assert.Equal(false, compression.IsLocallyStored);

            Assert.Equal(true, compression["doDynamicCompression"]);

            var compress = Assert.Throws <InvalidOperationException>(() => compression["doDynamicCompression"] = false);
            Assert.Equal(message, compress.Message);

            {
                // disable default document. Saved to web.config as this section can be overridden anywhere.
                ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                Assert.Equal(true, defaultDocumentSection["enabled"]);

                ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                Assert.Equal(7, filesCollection.Count);

                {
                    var first = filesCollection[0];
                    Assert.Equal("home1.html", first["value"]);
                    Assert.True(first.IsLocallyStored);
                }

                var second = filesCollection[1];
                Assert.Equal("Default.htm", second["value"]);
                Assert.False(second.IsLocallyStored);

                var third = filesCollection[2];
                Assert.Equal("Default.asp", third["value"]);
                Assert.False(third.IsLocallyStored);

                var remove = Assert.Throws <FileLoadException>(() => filesCollection.RemoveAt(4));
                Assert.Equal(
                    "Filename: \r\nError: This configuration section cannot be modified because it has been opened for read only access\r\n\r\n",
                    remove.Message);

                ConfigurationElement addElement = filesCollection.CreateElement();
                var add = Assert.Throws <InvalidOperationException>(() => filesCollection.AddAt(0, addElement));
                Assert.Equal(message, add.Message);

                Assert.Equal(7, filesCollection.Count);

                {
                    var first = filesCollection[0];
                    Assert.Equal("home1.html", first["value"]);
                    // TODO: why?
                    // Assert.IsFalse(first.IsLocallyStored);
                }

                Assert.Equal(7, filesCollection.Count);

                var clear = Assert.Throws <InvalidOperationException>(() => filesCollection.Clear());
                Assert.Equal(message, clear.Message);

                var delete = Assert.Throws <InvalidOperationException>(() => filesCollection.Delete());
                Assert.Equal(message, delete.Message);
            }
        }
Example #2
0
        protected override ConfigurationElementCollection GetCollection(IConfigurationService service)
        {
            ConfigurationSection section = service.GetSection("system.webServer/staticContent");

            return(section.GetCollection());
        }
 public ProtectedConfigurationSection(ConfigurationSection section)
 {
     DefaultProvider = (string)section["defaultProvider"];
     Providers       = new ProviderSettingsCollection(section.GetCollection("providers"));
 }
        protected override ConfigurationElementCollection GetCollection(IConfigurationService service)
        {
            ConfigurationSection section = service.GetSection("system.webServer/security/isapiCgiRestriction", null, false);

            return(section.GetCollection());
        }
        protected override ConfigurationElementCollection GetCollection(IConfigurationService service)
        {
            ConfigurationSection section = service.GetSection("system.webServer/isapiFilters", null, false);

            return(section.GetCollection());
        }
        protected override ConfigurationElementCollection GetCollection(IConfigurationService service)
        {
            ConfigurationSection requestFilteringSection = service.GetSection("system.webServer/security/requestFiltering");

            return(requestFilteringSection.GetCollection("fileExtensions"));
        }
Example #7
0
        public static void TestIisExpressMissingWebsiteConfig(ServerManager server)
        {
            Assert.Equal(5, server.ApplicationPools.Count);
            Assert.True(server.ApplicationPools.AllowsAdd);
            Assert.False(server.ApplicationPools.AllowsClear);
            Assert.False(server.ApplicationPools.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '/', '"', '|', '<', '>', ':', '*', '?', ']', '[', '+', '=', ';', ',', '@', '&' },
                ApplicationPoolCollection.InvalidApplicationPoolNameCharacters());

            Assert.Equal(12, server.Sites.Count);
            Assert.True(server.Sites.AllowsAdd);
            Assert.False(server.Sites.AllowsClear);
            Assert.False(server.Sites.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '/', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>' },
                SiteCollection.InvalidSiteNameCharacters());

            var siteDefaults = server.SiteDefaults;

            //Assert.Equal("localhost on *:8080 (http)", server.Sites[0].Bindings[0].ToShortString());
            Assert.Equal("%IIS_USER_HOME%\\Logs", siteDefaults.LogFile.Directory);
            Assert.Equal(LogFormat.W3c, siteDefaults.LogFile.LogFormat);
            Assert.Equal("%IIS_USER_HOME%\\TraceLogFiles", siteDefaults.TraceFailedRequestsLogging.Directory);
            Assert.True(siteDefaults.TraceFailedRequestsLogging.Enabled);
            Assert.True(siteDefaults.LogFile.Enabled);
            Assert.Equal("Clr4IntegratedAppPool", server.ApplicationDefaults.ApplicationPoolName);

            var pool = server.ApplicationPools[0];

            var model = pool.GetChildElement("processModel");
            var item  = model["maxProcesses"];

            Assert.Equal("Clr4IntegratedAppPool", pool.Name);
            Assert.Equal("v4.0", pool.ManagedRuntimeVersion);
            Assert.Equal(1, pool.ProcessModel.MaxProcesses);
            Assert.Equal(string.Empty, pool.ProcessModel.UserName);
#if IIS
            Assert.Equal(1L, item);
#else
            Assert.Equal(1U, item);
#endif

            var name = Assert.Throws <COMException>(() => pool.SetAttributeValue("name", ""));
            Assert.Equal("Invalid application pool name\r\n", name.Message);

            var time = Assert.Throws <COMException>(() => pool.ProcessModel.IdleTimeout = TimeSpan.MaxValue);
            Assert.Equal("Timespan value must be between 00:00:00 and 30.00:00:00 seconds inclusive, with a granularity of 60 seconds\r\n", time.Message);

            var site = server.Sites[0];
            Assert.Equal("WebSite1", site.Name);
            Assert.Equal(1, site.Bindings.Count);
            var binding = site.Bindings[0];
            Assert.Equal(IPAddress.Any, binding.EndPoint.Address);
            Assert.Equal(8080, binding.EndPoint.Port);
            Assert.Equal("localhost", binding.Host);
            Assert.Equal("*:8080:localhost", binding.ToString());
            Assert.True(site.Bindings.AllowsAdd);
            Assert.True(site.Bindings.AllowsClear);
            Assert.False(site.Bindings.AllowsRemove);

            var app = site.Applications[0];
            Assert.True(site.Applications.AllowsAdd);
            Assert.False(site.Applications.AllowsClear);
            Assert.False(site.Applications.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
                ApplicationCollection.InvalidApplicationPathCharacters());

            Assert.Equal("/", app.Path);
            var vDir = app.VirtualDirectories[0];
            Assert.True(app.VirtualDirectories.AllowsAdd);
            Assert.False(app.VirtualDirectories.AllowsClear);
            Assert.False(app.VirtualDirectories.AllowsRemove);
            Assert.Equal(
                new[] { '\\', '?', ';', ':', '@', '&', '=', '+', '$', ',', '|', '"', '<', '>', '*' },
                VirtualDirectoryCollection.InvalidVirtualDirectoryPathCharacters());

            Assert.Equal(Helper.IsRunningOnMono() ? "%JEXUS_TEST_HOME%/WebSite1" : "%JEXUS_TEST_HOME%\\WebSite1", vDir.PhysicalPath);

            {
                var config   = server.GetApplicationHostConfiguration();
                var section  = config.GetSection("system.applicationHost/log");
                var encoding = section.Attributes["logInUTF8"];
                Assert.Equal(true, encoding.Value);
                ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
                Assert.Equal(false, httpLoggingSection["dontLog"]);

                ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                Assert.Equal(true, defaultDocumentSection["enabled"]);
                ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                Assert.Equal(6, filesCollection.Count);

                var errorsSection    = config.GetSection("system.webServer/httpErrors");
                var errorsCollection = errorsSection.GetCollection();
                Assert.Equal(9, errorsCollection.Count);

                var anonymousSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication");
                var anonymousEnabled = (bool)anonymousSection["enabled"];
                Assert.True(anonymousEnabled);
                var value = anonymousSection["password"];
                Assert.Equal(string.Empty, value);

                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.False(windowsEnabled);

                windowsSection["enabled"] = true;
                server.CommitChanges();
            }

            {
                var config    = server.GetApplicationHostConfiguration();
                var locations = config.GetLocationPaths();
                Assert.Equal(3, locations.Length);

                var exception =
                    Assert.Throws <FileNotFoundException>(
                        () =>
                        config.GetSection(
                            "system.webServer/security/authentication/anonymousAuthentication",
                            "Default Web Site"));
                Assert.Equal(
                    "Filename: \r\nError: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/Default Web Site'\r\n\r\n",
                    exception.Message);
                Assert.Equal(null, exception.FileName);

                var anonymousSection = config.GetSection(
                    "system.webServer/security/authentication/anonymousAuthentication",
                    "WebSite2");
                var anonymousEnabled = (bool)anonymousSection["enabled"];
                Assert.True(anonymousEnabled);
                Assert.Equal("test", anonymousSection["userName"]);

                // Assert.Equal("123456", anonymousSection["password"]);
            }

            {
                // server config "Website1"
                var config = server.GetApplicationHostConfiguration();

                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
                Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
                Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
                Assert.Equal(false, windowsSection.IsLocked);
                Assert.Equal(true, windowsSection.IsLocallyStored);

                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.True(windowsEnabled);
                windowsSection["enabled"] = false;
                Assert.Equal(false, windowsSection["enabled"]);

                {
                    // disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
                    ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1");
                    Assert.Equal(false, httpLoggingSection["dontLog"]);
                    httpLoggingSection["dontLog"] = true;
                }

                {
                    ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging", "WebSite1/test");
                    // TODO:
                    // Assert.Equal(true, httpLoggingSection["dontLog"]);
                    httpLoggingSection["dontLog"] = false;
                }
            }

            var siteName = Assert.Throws <COMException>(() => server.Sites[0].Name = "");
            Assert.Equal("Invalid site name\r\n", siteName.Message);

            var limit = Assert.Throws <COMException>(() => server.Sites[0].Limits.MaxBandwidth = 12);
            Assert.Equal("Integer value must not be between 0 and 1023 inclusive\r\n", limit.Message);

            var appPath = Assert.Throws <COMException>(() => server.Sites[0].Applications[0].Path = "");
            Assert.Equal("Invalid application path\r\n", appPath.Message);

            var vDirPath =
                Assert.Throws <COMException>(() => server.Sites[0].Applications[0].VirtualDirectories[0].Path = "");
            Assert.Equal("Invalid virtual directory path\r\n", vDirPath.Message);

            {
                // site config "Website1"
                var config = server.Sites[0].Applications[0].GetWebConfiguration();

                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication");
                Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
                Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
                Assert.Equal(true, windowsSection.IsLocked);
                Assert.Equal(false, windowsSection.IsLocallyStored);

                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.True(windowsEnabled);
                var exception = Assert.Throws <FileLoadException>(() => windowsSection["enabled"] = false);
                Assert.Equal(
                    "This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault=\"Deny\"), or set explicitly by a location tag with overrideMode=\"Deny\" or the legacy allowOverride=\"false\".\r\n",
                    exception.Message);
                Assert.Equal(null, exception.FileName);

                var compression = config.GetSection("system.webServer/urlCompression");
                Assert.Equal(OverrideMode.Inherit, compression.OverrideMode);
                Assert.Equal(OverrideMode.Allow, compression.OverrideModeEffective);
                Assert.Equal(false, compression.IsLocked);
                Assert.Equal(false, compression.IsLocallyStored);

                Assert.Equal(true, compression["doDynamicCompression"]);

                compression["doDynamicCompression"] = false;

                {
                    // disable default document. Saved to web.config as this section can be overridden anywhere.
                    ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                    Assert.Equal(true, defaultDocumentSection["enabled"]);
                    defaultDocumentSection["enabled"] = false;

                    ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                    Assert.Equal(6, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("Default.htm", first["value"]);
                        Assert.False(first.IsLocallyStored);
                    }

                    var second = filesCollection[1];
                    Assert.Equal("Default.asp", second["value"]);
                    Assert.False(second.IsLocallyStored);

                    var third = filesCollection[2];
                    Assert.Equal("index.htm", third["value"]);
                    Assert.False(third.IsLocallyStored);

                    ConfigurationElement addElement = filesCollection.CreateElement();
                    addElement["value"] = @"home.html";
                    filesCollection.AddAt(0, addElement);

                    Assert.Equal(7, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("home.html", first["value"]);
                        // TODO: why?
                        // Assert.False(first.IsLocallyStored);
                    }

                    filesCollection.RemoveAt(4);
                    Assert.Equal(6, filesCollection.Count);

                    ConfigurationElement lastElement = filesCollection.CreateElement();
                    lastElement["value"] = @"home.html";
                    var dup = Assert.Throws <COMException>(() => filesCollection.Add(lastElement));
                    Assert.Equal(
                        "Filename: \r\nError: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'home.html'\r\n\r\n",
                        dup.Message);

                    lastElement["value"] = @"home2.html";
                    filesCollection.Add(lastElement);
                    Assert.Equal(7, filesCollection.Count);
                }

                //{
                //    var last = filesCollection[8];
                //    Assert.Equal("home2.html", last["value"]);
                //    // TODO: why?
                //    Assert.False(last.IsLocallyStored);
                //}

                {
                    // disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
                    ConfigurationSection httpLoggingSection = config.GetSection("system.webServer/httpLogging");
                    Assert.Equal(false, httpLoggingSection["dontLog"]);
                    Assert.Throws <FileLoadException>(() => httpLoggingSection["dontLog"] = true);
                }
                {
                    ConfigurationSection httpLoggingSection = config.GetSection(
                        "system.webServer/httpLogging",
                        "WebSite1/test");
                    // TODO:
                    //Assert.Equal(true, httpLoggingSection["dontLog"]);
                    Assert.Throws <FileLoadException>(() => httpLoggingSection["dontLog"] = false);
                }

                var errorsSection = config.GetSection("system.webServer/httpErrors");
                Assert.Equal(OverrideMode.Inherit, errorsSection.OverrideMode);
                Assert.Equal(OverrideMode.Allow, errorsSection.OverrideModeEffective);
                Assert.Equal(false, errorsSection.IsLocked);
                Assert.Equal(false, errorsSection.IsLocallyStored);

                var errorsCollection = errorsSection.GetCollection();
                Assert.Equal(9, errorsCollection.Count);

                var error = errorsCollection.CreateElement();
                var cast  = Assert.Throws <InvalidCastException>(() => error.SetAttributeValue("statusCode", "500"));
                Assert.Equal(Helper.IsRunningOnMono() ? "Cannot cast from source type to destination type." : "Specified cast is not valid.", cast.Message);

                var ex2 = Assert.Throws <COMException>(() => error["statusCode"] = 90000);
                Assert.Equal("Integer value must be between 400 and 999 inclusive\r\n", ex2.Message);

                error["statusCode"]             = 500;
                error["subStatusCode"]          = 55;
                error["prefixLanguageFilePath"] = string.Empty;
                error["responseMode"]           = "File";
                var ex1 = Assert.Throws <FileNotFoundException>(() => errorsCollection.Add(error));
                Assert.Equal("Filename: \r\nError: Element is missing required attributes path\r\n\r\n", ex1.Message);
                Assert.Equal(null, ex1.FileName);

                var ex = Assert.Throws <COMException>(() => error["path"] = "");
                Assert.Equal("String must not be empty\r\n", ex.Message);

                error["path"] = "test.htm";
                errorsCollection.Add(error);

                var staticContent = config.GetSection("system.webServer/staticContent").GetChildElement("clientCache");
                staticContent["cacheControlMode"] = "DisableCache";

                ConfigurationSection requestFilteringSection =
                    config.GetSection("system.webServer/security/requestFiltering");
                ConfigurationElement           hiddenSegmentsElement    = requestFilteringSection.GetChildElement("hiddenSegments");
                ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();
                Assert.Equal(8, hiddenSegmentsCollection.Count);

                var test = hiddenSegmentsCollection.CreateElement();
                test["segment"] = "test";
                hiddenSegmentsCollection.Add(test);

                var old = hiddenSegmentsCollection[0];
                hiddenSegmentsCollection.Remove(old);

                var section = config.GetSection("system.webServer/rewrite/rules");
                ConfigurationElementCollection collection = section.GetCollection();
                //collection.Clear();
                ////collection.Delete();

                //collection = section.GetCollection();
                //Assert.Equal(0, collection.Count);

                var newElement = collection.CreateElement();
                newElement["name"] = "test";
                collection.Add(newElement);
                Assert.Equal(2, collection.Count);

                collection.Clear();
                Assert.Equal(0, collection.Count);

                newElement         = collection.CreateElement();
                newElement["name"] = "test";
                collection.Add(newElement);
                Assert.Equal(1, collection.Count);
            }

            {
                // server config "Website1"
                var config = server.GetApplicationHostConfiguration();

                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite1");
                Assert.Equal(OverrideMode.Inherit, windowsSection.OverrideMode);
                Assert.Equal(OverrideMode.Deny, windowsSection.OverrideModeEffective);
                Assert.Equal(false, windowsSection.IsLocked);
                Assert.Equal(true, windowsSection.IsLocallyStored);

                var windowsEnabled = (bool)windowsSection["enabled"];
                Assert.False(windowsEnabled);
            }

            {
                Configuration config = server.GetApplicationHostConfiguration();

                var anonymousSection = config.GetSection(
                    "system.webServer/security/authentication/anonymousAuthentication",
                    "WebSite2");

                // anonymousSection["userName"] = "******";
                // anonymousSection["password"] = "******";
                ConfigurationSection windowsAuthenticationSection =
                    config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite2");
                windowsAuthenticationSection["enabled"] = true;

                ConfigurationElement extendedProtectionElement =
                    windowsAuthenticationSection.GetChildElement("extendedProtection");
                extendedProtectionElement["tokenChecking"] = @"Allow";
                extendedProtectionElement["flags"]         = @"None";

                var exception = Assert.Throws <COMException>(() => extendedProtectionElement["tokenChecking"] = @"NotExist");
                Assert.Equal("Enum must be one of None, Allow, Require\r\n", exception.Message);

                exception = Assert.Throws <COMException>(() => extendedProtectionElement["flags"] = @"NotExist");
                Assert.Equal("Flags must be some combination of None, Proxy, NoServiceNameCheck, AllowDotlessSpn, ProxyCohosting\r\n", exception.Message);

                ConfigurationElementCollection extendedProtectionCollection = extendedProtectionElement.GetCollection();

                ConfigurationElement spnElement = extendedProtectionCollection.CreateElement("spn");
                spnElement["name"] = @"HTTP/www.contoso.com";
                extendedProtectionCollection.Add(spnElement);

                ConfigurationElement spnElement1 = extendedProtectionCollection.CreateElement("spn");
                spnElement1["name"] = @"HTTP/contoso.com";
                extendedProtectionCollection.Add(spnElement1);

                server.CommitChanges();

                ConfigurationSection           rulesSection    = config.GetSection("system.webServer/rewrite/rules");
                ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();
                Assert.Equal(1, rulesCollection.Count);

                ConfigurationElement ruleElement = rulesCollection[0];
                Assert.Equal("lextudio2", ruleElement["name"]);
#if IIS
                Assert.Equal(0, ruleElement["patternSyntax"]);
#else
                Assert.Equal(0L, ruleElement["patternSyntax"]);
#endif
                Assert.Equal(true, ruleElement["stopProcessing"]);

                ConfigurationElement matchElement = ruleElement.GetChildElement("match");
                Assert.Equal(@"(.*)", matchElement["url"]);

                ConfigurationElement actionElement = ruleElement.GetChildElement("action");
#if IIS
                Assert.Equal(1, actionElement["type"]);
#else
                Assert.Equal(1L, actionElement["type"]);
#endif
                Assert.Equal("/www/{R:0}", actionElement["url"]);
            }

            // remove application pool
            Assert.False(server.ApplicationPools.AllowsRemove);
            Assert.Equal(5, server.ApplicationPools.Count);
            server.ApplicationPools.RemoveAt(4);
            Assert.Equal(4, server.ApplicationPools.Count);

            // remove binding
            server.Sites[1].Bindings.RemoveAt(1);

            // remove site
            server.Sites.RemoveAt(4);

            // remove application
            var site1 = server.Sites[9];
            site1.Applications.RemoveAt(1);

            // remove virtual directory
            var application = server.Sites[2].Applications[0];
            application.VirtualDirectories.RemoveAt(1);

            server.CommitChanges();
        }
Example #8
0
        public async void AddSite()
        {
            const string Current      = @"applicationHost.config";
            const string Original     = @"original.config";
            const string OriginalMono = @"original.mono.config";

            if (Helper.IsRunningOnMono())
            {
                File.Copy("Website1/original.config", "Website1/web.config", true);
                File.Copy(OriginalMono, Current, true);
            }
            else
            {
                File.Copy("Website1\\original.config", "Website1\\web.config", true);
                File.Copy(Original, Current, true);
            }

            Environment.SetEnvironmentVariable(
                "JEXUS_TEST_HOME",
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            var serverManager = new ServerManager(Current)
            {
                Mode = WorkingMode.IisExpress
            };

            Configuration                  config          = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection           sitesSection    = config.GetSection("system.applicationHost/sites");
            ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

            ConfigurationElement siteElement = sitesCollection.CreateElement("site");

            siteElement["name"]            = @"Contoso";
            siteElement["id"]              = 2;
            siteElement["serverAutoStart"] = true;

            ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
            ConfigurationElement           bindingElement     = bindingsCollection.CreateElement("binding");

            bindingElement["protocol"]           = @"http";
            bindingElement["bindingInformation"] = @"*:80:www.contoso.com";
            bindingsCollection.Add(bindingElement);

            ConfigurationElementCollection siteCollection     = siteElement.GetCollection();
            ConfigurationElement           applicationElement = siteCollection.CreateElement("application");

            applicationElement["path"] = @"/";
            ConfigurationElementCollection applicationCollection   = applicationElement.GetCollection();
            ConfigurationElement           virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");

            virtualDirectoryElement["path"]         = @"/";
            virtualDirectoryElement["physicalPath"] = @"C:\Inetpub\www.contoso.com\wwwroot";
            applicationCollection.Add(virtualDirectoryElement);
            siteCollection.Add(applicationElement);
            sitesCollection.Add(siteElement);

            serverManager.CommitChanges();

            const string Expected     = @"expected_site_add.config";
            const string ExpectedMono = @"expected_site_add.mono.config";

            XmlAssert.Equal(
                Helper.IsRunningOnMono()
                    ? Path.Combine("Main", ExpectedMono)
                    : Path.Combine("Main", Expected),
                Current);
        }
Example #9
0
        public static void TestIisExpressMissingWebsiteConfig(ServerManager server)
        {
            {
                var config = server.GetApplicationHostConfiguration();

                var windowsSection =
                    config.GetSection("system.webServer/security/authentication/windowsAuthentication");
                windowsSection["enabled"] = true;
                server.CommitChanges();
            }
            {
                // server config "Website1"
                var config         = server.GetApplicationHostConfiguration();
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication",
                                                       "WebSite1");
                windowsSection["enabled"] = false;
                {
                    // disable logging. Saved in applicationHost.config, as it cannot be overridden in web.config.
                    ConfigurationSection httpLoggingSection =
                        config.GetSection("system.webServer/httpLogging", "WebSite1");
                    httpLoggingSection["dontLog"] = true;
                }

                {
                    ConfigurationSection httpLoggingSection =
                        config.GetSection("system.webServer/httpLogging", "WebSite1/test");
                    httpLoggingSection["dontLog"] = false;
                }
            }
            {
                // site config "Website1"
                var config      = server.Sites[0].Applications[0].GetWebConfiguration();
                var compression = config.GetSection("system.webServer/urlCompression");
                compression["doDynamicCompression"] = false;
                {
                    // disable default document. Saved to web.config as this section can be overridden anywhere.
                    ConfigurationSection defaultDocumentSection = config.GetSection("system.webServer/defaultDocument");
                    Assert.Equal(true, defaultDocumentSection["enabled"]);
                    defaultDocumentSection["enabled"] = false;

                    ConfigurationElementCollection filesCollection = defaultDocumentSection.GetCollection("files");
                    Assert.Equal(6, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("Default.htm", first["value"]);
                        Assert.False(first.IsLocallyStored);
                    }

                    var second = filesCollection[1];
                    Assert.Equal("Default.asp", second["value"]);
                    Assert.False(second.IsLocallyStored);

                    var third = filesCollection[2];
                    Assert.Equal("index.htm", third["value"]);
                    Assert.False(third.IsLocallyStored);

                    ConfigurationElement addElement = filesCollection.CreateElement();
                    addElement["value"] = @"home.html";
                    filesCollection.AddAt(0, addElement);

                    Assert.Equal(7, filesCollection.Count);

                    {
                        var first = filesCollection[0];
                        Assert.Equal("home.html", first["value"]);
                        // TODO: why?
                        // Assert.False(first.IsLocallyStored);
                    }

                    filesCollection.RemoveAt(4);
                    Assert.Equal(6, filesCollection.Count);

                    ConfigurationElement lastElement = filesCollection.CreateElement();
                    lastElement["value"] = @"home.html";
                    var dup = Assert.Throws <COMException>(() => filesCollection.Add(lastElement));
#if IIS
                    Assert.Equal(
                        "Filename: \r\nError: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'home.html'\r\n\r\n",
                        dup.Message);
#else
                    Assert.Equal(
                        $"Filename: \\\\?\\{config.FileContext.FileName}\r\nLine number: 0\r\nError: Cannot add duplicate collection entry of type 'add' with unique key attribute 'value' set to 'home.html'\r\n\r\n",
                        dup.Message);
#endif
                    lastElement["value"] = @"home2.html";
                    filesCollection.Add(lastElement);
                    Assert.Equal(7, filesCollection.Count);
                }

                var errorsSection    = config.GetSection("system.webServer/httpErrors");
                var errorsCollection = errorsSection.GetCollection();
                var error            = errorsCollection.CreateElement();
                error["statusCode"]             = 500;
                error["subStatusCode"]          = 55;
                error["prefixLanguageFilePath"] = string.Empty;
                error["responseMode"]           = "File";
                error["path"] = "test.htm";
                errorsCollection.Add(error);

                var staticContent = config.GetSection("system.webServer/staticContent").GetChildElement("clientCache");
                staticContent["cacheControlMode"] = "DisableCache";

                ConfigurationSection requestFilteringSection =
                    config.GetSection("system.webServer/security/requestFiltering");
                ConfigurationElement           hiddenSegmentsElement    = requestFilteringSection.GetChildElement("hiddenSegments");
                ConfigurationElementCollection hiddenSegmentsCollection = hiddenSegmentsElement.GetCollection();
                var test = hiddenSegmentsCollection.CreateElement();
                test["segment"] = "test";
                hiddenSegmentsCollection.Add(test);
                var old = hiddenSegmentsCollection[0];
                hiddenSegmentsCollection.Remove(old);

                var section = config.GetSection("system.webServer/rewrite/rules");
                ConfigurationElementCollection collection = section.GetCollection();
                collection.Clear();
                var newElement = collection.CreateElement();
                newElement["name"] = "test";
                collection.Add(newElement);
            }

            {
                // server config "Website1"
                var config = server.GetApplicationHostConfiguration();
                // enable Windows authentication
                var windowsSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication",
                                                       "WebSite1");
                var windowsEnabled = (bool)windowsSection["enabled"];
            }
            {
                Configuration config = server.GetApplicationHostConfiguration();

                var anonymousSection = config.GetSection(
                    "system.webServer/security/authentication/anonymousAuthentication",
                    "WebSite2");
                ConfigurationSection windowsAuthenticationSection =
                    config.GetSection("system.webServer/security/authentication/windowsAuthentication", "WebSite2");
                windowsAuthenticationSection["enabled"] = true;

                ConfigurationElement extendedProtectionElement =
                    windowsAuthenticationSection.GetChildElement("extendedProtection");
                extendedProtectionElement["tokenChecking"] = @"Allow";
                extendedProtectionElement["flags"]         = @"None";
                ConfigurationElementCollection extendedProtectionCollection =
                    extendedProtectionElement.GetCollection();

                ConfigurationElement spnElement = extendedProtectionCollection.CreateElement("spn");
                spnElement["name"] = @"HTTP/www.contoso.com";
                extendedProtectionCollection.Add(spnElement);

                ConfigurationElement spnElement1 = extendedProtectionCollection.CreateElement("spn");
                spnElement1["name"] = @"HTTP/contoso.com";
                extendedProtectionCollection.Add(spnElement1);

                server.CommitChanges();
            }
            // remove application pool
            Assert.False(server.ApplicationPools.AllowsRemove);
            Assert.Equal(5, server.ApplicationPools.Count);
            server.ApplicationPools.RemoveAt(4);
            Assert.Equal(4, server.ApplicationPools.Count);

            // remove binding
            server.Sites[1].Bindings.RemoveAt(1);

            // remove site
            server.Sites.RemoveAt(4);

            // remove application
            var site1 = server.Sites[9];
            site1.Applications.RemoveAt(1);

            // remove virtual directory
            var application = server.Sites[2].Applications[0];
            application.VirtualDirectories.RemoveAt(1);

            server.CommitChanges();
        }
Example #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Indique la IP con la que desea trabajar: ");
            string IP = Console.ReadLine();

            if (string.IsNullOrEmpty(IP))
            {
                Console.WriteLine("No se ingreso una IP, por tanto termino el programa. Gracias por hacerme perder mi tiempo ¬¬");
                return;
            }

            //Probar si la IP es una IP valida
            if (IsValidateIP(IP) == false)
            {
                Console.WriteLine("Tss, ingresaste una IP valida. Gracias por hacerme perder mi tiempo ¬¬");
                return;
            }

            //Preguntamos si se quiere agregar o eliminar
            Console.WriteLine("Deseas eliminar(1) o agregar (2) la IP?");
            string opcionEliminar = Console.ReadLine();

            bool agregar = opcionEliminar == "2";

            using (ServerManager serverManager = new ServerManager())
            {
                Configuration configuration = serverManager.GetApplicationHostConfiguration();

                List <string> sitiosIIs = new List <string>()
                {
                    "adminEcommerce", "clientesEcomm", "disponibilidadecom", "exploracionecom", "menuecom", "notificacionesecom", "pedidosecom"
                };



                foreach (string sitioIis in sitiosIIs)
                {
                    ConfigurationSection           ipSecuritySection    = configuration.GetSection("system.webServer/security/ipSecurity", sitioIis);
                    ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();

                    ConfigurationElement existingElement = ipSecurityCollection.FirstOrDefault(x => x.Attributes["ipAddress"].Value.ToString() == IP);

                    //Si quiere agregar y no existe el elemento, lo agrego
                    if (agregar && existingElement == null)
                    {
                        ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");
                        addElement["ipAddress"] = IP;
                        addElement["allowed"]   = true;
                        Console.WriteLine($"[ADD] Se agrega el elemento {IP} en el sitio: {sitioIis}");
                        ipSecurityCollection.Add(addElement);
                    }
                    else
                    {
                        ConfigurationElement removeElement = ipSecurityCollection.FirstOrDefault(x => x.Attributes["ipAddress"].Value.ToString() == IP);

                        //Si ya esta, lo elimino
                        if (removeElement != null)
                        {
                            Console.WriteLine($"[DELETE] Se encuentra el elemento {IP} en el sitio: {sitioIis}, se remueve");
                            ipSecurityCollection.Remove(removeElement);
                        }
                    }
                }

                serverManager.CommitChanges();
            }
        }
Example #11
0
        private static void UpdateIIS(String rewriteXmlNode)
        {
            if (rewriteXmlNode != "")
            {
                using (ServerManager serverManager = new ServerManager())
                {
                    Configuration configapp = serverManager.GetApplicationHostConfiguration();
                    try
                    {
                        ConfigurationSection webServerSection = configapp.GetSection("system.webServer/rewrite");

                        ConfigurationElementCollection webServerCollection = webServerSection.GetCollection();
                        ConfigurationElement           addElement          = webServerCollection.CreateElement("rewrite");
                        webServerCollection.Add(addElement);
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.ToString());
                        throw ex;
                    }
                    serverManager.CommitChanges();
                }

                File.Copy("C:\\Windows\\System32\\inetsrv\\config\\applicationHost.config", "C:\\Windows\\System32\\inetsrv\\config\\applicationHost.copy", true);
                var hostconfigpath = @"C:\Windows\System32\inetsrv\config\applicationHost.copy";
                if (File.Exists(hostconfigpath))
                {
                    try
                    {
                        var xmlDoc = new XmlDocument();
                        xmlDoc.Load(hostconfigpath);

                        // create a global element which will be injected
                        XmlNode newRuleOuter = xmlDoc.CreateNode(XmlNodeType.Element, "newRule", null);
                        newRuleOuter.InnerXml = rewriteXmlNode;
                        XmlNode newRule = newRuleOuter.SelectSingleNode("rule");

                        var rewriteNode = xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite");
                        if (rewriteNode == null)
                        {
                            var     webServerNod = xmlDoc.SelectSingleNode("configuration/system.webServer"); // should always exists
                            XmlNode rewriteRules = xmlDoc.CreateNode(XmlNodeType.Element, "rewrite", null);
                            webServerNod?.AppendChild(rewriteRules);
                            rewriteNode = xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite");
                        }

                        var globalRulesNode = xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite/globalRules");
                        if (globalRulesNode == null)
                        {
                            // create globalrules node and inject rule node/
                            XmlNode newglobalRules = xmlDoc.CreateNode(XmlNodeType.Element, "globalRules", null);
                            newglobalRules.InnerXml = rewriteXmlNode;
                            rewriteNode?.AppendChild(newglobalRules);
                            globalRulesNode = xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite/globalRules");
                        }

                        // rules exists, find name="Spam-Referrals" and replace, if diff
                        XmlNode      newruleNode = xmlDoc.CreateNode(XmlNodeType.Element, "rule", null);
                        XmlAttribute nameatt     = xmlDoc.CreateAttribute("name");
                        nameatt.Value = "Spam-Referrals";
                        newruleNode.Attributes.Append(nameatt);
                        var innerXml = rewriteXmlNode.Replace("<rule name=\"Spam-Referrals\">", "").Replace("</rule>", "").Trim() + "\r\n";
                        newruleNode.InnerXml = innerXml;
                        var ruleNode = xmlDoc.SelectSingleNode("configuration/system.webServer/rewrite/globalRules/rule[@name='Spam-Referrals']");
                        if (ruleNode == null)
                        {
                            globalRulesNode.AppendChild(newruleNode);
                        }
                        else
                        {
                            globalRulesNode.ReplaceChild(newruleNode, ruleNode);
                        }

                        xmlDoc.Save(".\\spammerblock_config.xml");

                        // now we've created it overwrite live config file
                        File.Copy("C:\\Windows\\System32\\inetsrv\\config\\applicationHost.config", "C:\\Windows\\System32\\inetsrv\\config\\applicationHost.copy", true);
                        File.Copy(".\\spammerblock_config.xml", "C:\\Windows\\System32\\inetsrv\\config\\applicationHost.config", true);
                    }
                    catch (Exception e)
                    {
                        File.WriteAllText(".\\spammerblock_ERROR.txt", e.Message);
                    }
                }
            }
        }
Example #12
0
        //添加ftp站点
        public void createFTP(string ftpname, string ftpPath, string username, string ipaddress)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetApplicationHostConfiguration();

                ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");

                ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

                ConfigurationElement siteElement = sitesCollection.CreateElement("site");
                siteElement["name"] = ftpname;
                siteElement["id"]   = GetNewSiteID();

                ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");

                ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
                bindingElement["protocol"]           = @"ftp";
                bindingElement["bindingInformation"] = ipaddress + @":21:";
                bindingsCollection.Add(bindingElement);

                //ftp 授权规则
                ConfigurationSection           authorizationSection    = config.GetSection("system.ftpServer/security/authorization");
                ConfigurationElementCollection authorizationCollection = authorizationSection.GetCollection();
                // 清除子节点授权,防止有残余
                authorizationCollection.Clear();
                ConfigurationElement addElement1 = authorizationCollection.CreateElement("add");
                addElement1["accessType"]  = @"Allow";
                addElement1["users"]       = username;
                addElement1["permissions"] = @"Read,Write";
                authorizationCollection.Add(addElement1);

                ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");
                //设置ftp ssl
                ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");
                ConfigurationElement sslElement      = securityElement.GetChildElement("ssl");
                //sslElement["serverCertHash"] = @"53FC3C74A1978C734751AB7A14A3E48F70A58A84";
                sslElement["controlChannelPolicy"] = @"SslAllow";
                sslElement["dataChannelPolicy"]    = @"SslAllow";
                // 设置ftp身份验证
                ConfigurationElement authenticationElement = securityElement.GetChildElement("authentication");
                //ConfigurationElementCollection authenticationElementCollection = authorizationSection.GetCollection();
                ConfigurationElement basicAuthenticationElement = authenticationElement.GetChildElement("basicAuthentication");
                basicAuthenticationElement["enabled"] = @"true";
                ConfigurationElement anonymousAuthenticationElement = authenticationElement.GetChildElement("anonymousAuthentication");
                anonymousAuthenticationElement["enabled"] = @"true";



                ConfigurationElementCollection siteCollection     = siteElement.GetCollection();
                ConfigurationElement           applicationElement = siteCollection.CreateElement("application");
                applicationElement["path"] = @"/";

                ConfigurationElementCollection applicationCollection   = applicationElement.GetCollection();
                ConfigurationElement           virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
                virtualDirectoryElement["path"]         = @"/";
                virtualDirectoryElement["physicalPath"] = ftpPath;
                applicationCollection.Add(virtualDirectoryElement);
                siteCollection.Add(applicationElement);
                sitesCollection.Add(siteElement);
                serverManager.CommitChanges();
            }
        }
        internal static bool UpdateAuthenticationSettingsAndProviders(ServerManager serverManager, string siteName, string virtualPath, MultiValuedProperty <AuthenticationMethod> authMethods)
        {
            bool                 flag = false;
            string               text = siteName + virtualPath;
            Configuration        applicationHostConfiguration = serverManager.GetApplicationHostConfiguration();
            ConfigurationSection section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/anonymousAuthentication", text);

            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", false);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/basicAuthentication", text);
            bool flag2 = authMethods.Contains(AuthenticationMethod.Basic);

            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/clientCertificateMappingAuthentication", text);
            flag2   = authMethods.Contains(AuthenticationMethod.Certificate);
            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/digestAuthentication", text);
            flag2   = authMethods.Contains(AuthenticationMethod.Digest);
            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/iisClientCertificateMappingAuthentication", text);
            flag   |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", false);
            section = applicationHostConfiguration.GetSection("system.webServer/security/authentication/windowsAuthentication", text);
            bool flag3 = authMethods.Contains(AuthenticationMethod.Negotiate);
            bool flag4 = authMethods.Contains(AuthenticationMethod.Kerberos);
            bool flag5 = authMethods.Contains(AuthenticationMethod.Ntlm);
            bool flag6 = authMethods.Contains(AuthenticationMethod.LiveIdNegotiate);

            flag2 = (flag3 || flag4 || flag5 || flag6);
            flag |= IISConfigurationUtilities.UpdateSectionAttribute(section, "enabled", flag2);
            flag |= IISConfigurationUtilities.UpdateSectionAttribute(section, "useKernelMode", false);
            if (flag2)
            {
                ConfigurationElementCollection collection = section.GetCollection("providers");
                int  num   = (flag3 ? 1 : 0) + (flag4 ? 1 : 0) + (flag5 ? 1 : 0);
                bool flag7 = false;
                if (collection.Count != num)
                {
                    flag7 = true;
                }
                else
                {
                    int num2 = 0;
                    if (flag6)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "Negotiate:MSOIDSSP");
                        num2++;
                    }
                    if (flag3)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "Negotiate");
                        num2++;
                    }
                    if (flag4)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "Negotiate:Kerberos");
                        num2++;
                    }
                    if (flag5)
                    {
                        flag7 |= ((string)collection[num2].Attributes["value"].Value != "NTLM");
                        num2++;
                    }
                }
                if (flag7)
                {
                    flag = true;
                    collection.Clear();
                    if (flag6)
                    {
                        ConfigurationElement configurationElement = collection.CreateElement("add");
                        configurationElement["value"] = "Negotiate:MSOIDSSP";
                        collection.Add(configurationElement);
                    }
                    if (flag3)
                    {
                        ConfigurationElement configurationElement2 = collection.CreateElement("add");
                        configurationElement2["value"] = "Negotiate";
                        collection.Add(configurationElement2);
                    }
                    if (flag4)
                    {
                        ConfigurationElement configurationElement3 = collection.CreateElement("add");
                        configurationElement3["value"] = "Negotiate:Kerberos";
                        collection.Add(configurationElement3);
                    }
                    if (flag5)
                    {
                        ConfigurationElement configurationElement4 = collection.CreateElement("add");
                        configurationElement4["value"] = "NTLM";
                        collection.Add(configurationElement4);
                    }
                }
            }
            return(flag);
        }
 public ProtectedConfigurationSection(ConfigurationSection section)
 {
     DefaultProvider = (string)section["defaultProvider"];
     Providers = new ProviderSettingsCollection(section.GetCollection("providers"));
 }
Example #15
0
        /// <summary>
        /// Configures the site for ACME validation without generating an overly complicated web.config
        /// </summary>
        /// <param name="target"></param>
        public void PrepareSite(Target target)
        {
            var config = ServerManager.GetApplicationHostConfiguration();
            var siteId = target.ValidationSiteId ?? target.TargetSiteId ?? -1;
            var site   = GetWebSite(siteId);

            // Only do it for the .well-known folder, do not compromise security for other parts of the application
            var wellKnown     = $"/{_wellKnown}";
            var acmeChallenge = $"/{_wellKnown}/{_acmeChallenge}";
            var parentPath    = site.Name + wellKnown;
            var path          = site.Name + acmeChallenge;

            // Create application
            var rootApp  = site.Applications.FirstOrDefault(x => x.Path == "/");
            var rootVdir = rootApp.VirtualDirectories.FirstOrDefault(x => x.Path == "/");
            var wkApp    = site.Applications.FirstOrDefault(a => a.Path == wellKnown);
            var acApp    = site.Applications.FirstOrDefault(a => a.Path == acmeChallenge);
            var wkVdir   = wkApp?.VirtualDirectories.FirstOrDefault(v => v.Path == "/");
            var acVdir   = acApp?.VirtualDirectories.FirstOrDefault(v => v.Path == "/");

            if (wkApp == null)
            {
                wkApp = site.Applications.CreateElement();
                wkApp.ApplicationPoolName = rootApp.ApplicationPoolName;
                wkApp.Path = wellKnown;
                site.Applications.Add(wkApp);
            }
            if (acApp == null)
            {
                acApp = site.Applications.CreateElement();
                acApp.ApplicationPoolName = rootApp.ApplicationPoolName;
                acApp.Path = acmeChallenge;
                site.Applications.Add(acApp);
            }
            if (wkVdir == null)
            {
                wkVdir      = wkApp.VirtualDirectories.CreateElement();
                wkVdir.Path = "/";
                wkApp.VirtualDirectories.Add(wkVdir);
                wkVdir.PhysicalPath = $"{rootVdir.PhysicalPath.TrimEnd('\\')}\\{_wellKnown}\\";
            }
            if (acVdir == null)
            {
                acVdir      = wkApp.VirtualDirectories.CreateElement();
                acVdir.Path = "/";
                acApp.VirtualDirectories.Add(acVdir);
            }
            acVdir.PhysicalPath = $"{rootVdir.PhysicalPath.TrimEnd('\\')}\\{_wellKnown}\\{_acmeChallenge}\\";

            // Enabled Anonymous authentication
            ConfigurationSection anonymousAuthenticationSection = config.GetSection(_anonymousAuthenticationSection, path);

            anonymousAuthenticationSection["enabled"] = true;

            // Disable "Require SSL"
            ConfigurationSection accessSecuritySection = config.GetSection(_accessSecuritySection, path);

            accessSecuritySection["sslFlags"] = "None";

            // Disable IP restrictions
            ConfigurationSection ipSecuritySection = config.GetSection(_ipSecuritySection, path);

            ipSecuritySection["allowUnlisted"] = true;

            ConfigurationSection globalModules = config.GetSection(_modulesSection);
            var globals = globalModules.GetCollection().Select(gm => gm.GetAttributeValue("name")).ToList();

            var local = ServerManager.GetWebConfiguration(site.Name, path);
            ConfigurationSection localModules = local.GetSection(_modulesSection);

            ConfigurationSection           modulesSection    = config.GetSection(_modulesSection, path);
            ConfigurationElementCollection modulesCollection = modulesSection.GetCollection();

            modulesSection["runAllManagedModulesForAllRequests"] = false;
            foreach (var module in localModules.GetCollection())
            {
                var moduleName = module.GetAttributeValue("name");
                if (!globals.Contains(moduleName))
                {
                    ConfigurationElement newModule = modulesCollection.CreateElement("remove");
                    newModule.SetAttributeValue("name", moduleName);
                    modulesCollection.Add(newModule);
                }
            }

            // Configure handlers
            ConfigurationSection           handlerSection     = config.GetSection(_handlerSection, path);
            ConfigurationElementCollection handlersCollection = handlerSection.GetCollection();

            handlersCollection.Clear();
            ConfigurationElement addElement = handlersCollection.CreateElement("add");

            addElement["modules"]      = "StaticFileModule,DirectoryListingModule";
            addElement["name"]         = "StaticFile";
            addElement["resourceType"] = "Either";
            addElement["path"]         = "*";
            addElement["verb"]         = "GET";
            handlersCollection.Add(addElement);

            // Disable URL rewrite
            if (_rewriteModule)
            {
                try
                {
                    ConfigurationSection           urlRewriteSection    = config.GetSection(_urlRewriteSection, path);
                    ConfigurationElementCollection urlRewriteCollection = urlRewriteSection.GetCollection();
                    urlRewriteCollection.Clear();
                }
                catch { }
            }

            // Save
            Commit();
        }
 static internal List<string> GetProviders(ConfigurationSection section, string providerElementName, string valueAttributeName)
 {
     List<string> providerList = new List<string>();
     foreach (ConfigurationElement element in section.GetCollection(providerElementName))
     {
         providerList.Add((string)ServerManagerWrapper.GetAttributeValue(element, valueAttributeName));
     }
     return providerList;
 }
Example #17
0
        /// <summary>
        /// Deploy fast-cgi settings
        /// </summary>
        protected void DeployFasctCgi()
        {
            var limits = this.Deployment.GetApplicationLimits();

            using (ServerManager serverManager = new ServerManager())
            {
                this.Logger.LogWarning(false, "Deploying fastCgi based applications causes IIS to internally reset to pick the new configuration because fastCgi is configured at the server level.");

                var phpRuntime  = this.GetFastCgiExe();
                var iniFilePath = this.GetIniFilePath();
                var phpIniFile  = this.GetIniFilePath();

                string siteAlias = this.Deployment.getShortId();

                // fastCgi settings in IIS can only be set at the HOSTS level
                // we found no way to set this at a web.config level.
                Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
                ConfigurationSection section = config.GetSection("system.webServer/fastCgi");
                ConfigurationElement cfs     = null;

                // Each fastCgi in IIS is a unique combination of RUNTIME_PATH|ARGUMENTS, try to find
                // the current application.
                foreach (ConfigurationElement sec in section.GetCollection())
                {
                    // Cada aplicación se identifica de manera única por la combincación de atributo y path de ejecución.
                    if (sec.HasValue("arguments", siteAlias) && sec.HasValue("fullPath", phpRuntime))
                    {
                        cfs = sec;
                        break;
                    }
                }

                // We need to keep track if the element already existed
                // in the configuration, or it is new.
                bool addApplication = false;
                ConfigurationElementCollection elems = section.GetCollection();
                if (cfs == null)
                {
                    cfs            = elems.CreateElement("application");
                    addApplication = true;
                }

                // In this deployment we are not really passing
                // any argments to PHP, simply use the site Alias to
                // isolate each PHP site.
                // OJO: PONER EL SITE ALIAS AQUÍ NO ES ALGO
                // GRATUITO. LUEGO EN EL WEB.CONFIG DE LA PROPIA
                // APLICACIÓN DEBE ESTAR EXACTAMENTE IGUAL.
                cfs.SetAttributeValue("arguments", siteAlias);

                // Set reasonable defaults, even if the user configuration says differently
                var instanceMaxRequests = this.PhpSettings.instanceMaxRequests > 200 ? this.PhpSettings.instanceMaxRequests : 10000;
                var maxInstances        = this.PhpSettings.maxInstances > 3 ? this.PhpSettings.maxInstances : 10;
                var activityTimeout     = this.PhpSettings.activityTimeout > 100 ? this.PhpSettings.activityTimeout : 600;
                var requestTimeout      = this.PhpSettings.requestTimeout > 60 ? this.PhpSettings.requestTimeout : 300;

                // Ensure that all values are within the limits
                if (maxInstances > limits.FastCgiMaxInstances && limits.FastCgiMaxInstances > 0)
                {
                    maxInstances = limits.FastCgiMaxInstances.Value;
                }

                // Runtime Path.
                cfs.SetAttributeValue("fullPath", phpRuntime);
                cfs.SetAttributeValue("maxInstances", maxInstances);
                cfs.SetAttributeValue("activityTimeout", activityTimeout);
                cfs.SetAttributeValue("requestTimeout", requestTimeout);
                cfs.SetAttributeValue("instanceMaxRequests", instanceMaxRequests);

                // Make sure that changes to PHP.ini are refreshed properly
                if (File.Exists(iniFilePath))
                {
                    cfs.SetAttributeValue("monitorChangesTo", iniFilePath);
                }

                // Este setting no sirve para nada según -E- de MS porque
                // la implementación de FastCGI está mal hecha en IIS.
                // Los eventos internos de señal no se llegan a ejecutar nunca,
                // lo único que consigues es demorar el cierre de instancias.
                cfs.SetAttributeValue("signalBeforeTerminateSeconds", 0);

                if (!File.Exists(phpIniFile))
                {
                    throw new Exception("PHP.ini file not found. This will break the IIS FastCgiModule when using monitorChangesTo feature.");
                }

                // Retrieve the environment variables.
                ConfigurationElement           cfgEnvironment = cfs.GetChildElement("environmentVariables");
                ConfigurationElementCollection a = cfgEnvironment.GetCollection();

                // This is fastcgi specific.
                a.AddOrUpdateConfigurationElementInCollection("PHP_FCGI_MAX_REQUESTS", instanceMaxRequests.ToString());

                // Add all the environment variables.
                var environmentVariables = this.GetEnvironmentVariables();
                foreach (var p in environmentVariables)
                {
                    a.AddOrUpdateConfigurationElementInCollection(p.Key, p.Value);
                }

                if (addApplication)
                {
                    elems.Add(cfs);
                }

                // Cleanup any fastCgi applications that point to non-existent handlers
                // see the comments in FastCgiRemove() as to why this is here.
                var fastCgiHandlers = section.GetCollection();
                foreach (ConfigurationElement sec in fastCgiHandlers.ToList())
                {
                    if (sec.RawAttributes.Keys.Contains("fullPath"))
                    {
                        string fullPath = sec.GetAttributeValue("fullPath").ToString();
                        if (!File.Exists(fullPath))
                        {
                            this.Logger.LogInfo(true, "Removed stale fastCgi handler {0}", fullPath);
                            fastCgiHandlers.Remove(sec);
                        }
                    }
                }

                UtilsIis.CommitChanges(serverManager);
            }
        }