public virtual object Create(Object parent, Object configContextObj, XmlNode section)
        {
            // if called through client config don't even load HttpRuntime
            if (!HandlerBase.IsServerConfiguration(configContextObj))
            {
                return(null);
            }


            HttpConfigurationContext configContext = configContextObj as HttpConfigurationContext;

            // section handlers can run in client mode with ConfigurationSettings.GetConfig("sectionName")
            // detect this case and return null to be ensure no exploits from secure client scenarios
            // see ASURT 123738
            if (configContext == null)
            {
                return(null);
            }

            if (HandlerBase.IsPathAtAppLevel(configContext.VirtualPath) == PathLevel.BelowApp)
            {
                throw new ConfigurationException(
                          HttpRuntime.FormatResourceString(SR.Cannot_specify_below_app_level, section.Name),
                          section);
            }

            return(new SecurityPolicyConfig((SecurityPolicyConfig)parent, section, ConfigurationException.GetXmlNodeFilename(section)));
        }
            private static void AddAllAssembliesFromAppDomainBinDirectory(
                CompilationConfiguration result, XmlNode child)
            {
                // Get the path to the bin directory
                string binPath = HttpRuntime.BinDirectoryInternal;

                FileInfo[] binDlls;

                if (!FileUtil.DirectoryExists(binPath))
                {
                    // This is expected to fail if there is no 'bin' dir
                    Debug.Trace("Template", "Failed to access bin dir \"" + binPath + "\"");
                }
                else
                {
                    DirectoryInfo binPathDirectory = new DirectoryInfo(binPath);
                    // Get a list of all the DLL's in the bin directory
                    binDlls = binPathDirectory.GetFiles("*.dll");

                    string configFile = ConfigurationException.GetXmlNodeFilename(child);

                    for (int i = 0; i < binDlls.Length; i++)
                    {
                        string assemblyName = Util.GetAssemblyNameFromFileName(binDlls[i].Name);

                        // Remember the config file location info, in case an error
                        // occurs later when we try to load the assembly (ASURT 72183)
                        int configFileLine = ConfigurationException.GetXmlNodeLineNumber(child);
                        result._assemblies[assemblyName] = new object[]
                        { configFile, configFileLine, true /*starDirective*/ };
                    }
                }
            }
示例#3
0
        /// <summary>
        /// Returns the name of the file specified node is defined in.
        /// </summary>
        /// <param name="node">Node to get the file name for.</param>
        /// <returns>The name of the file specified node is defined in.</returns>
        public static string GetFileName(XmlNode node)
        {
            if (node is ITextPosition)
            {
                return(((ITextPosition)node).Filename);
            }
#if !NET_2_0
            return(ConfigurationException.GetXmlNodeFilename(node));
#else
            return(ConfigurationErrorsException.GetFilename(node));
#endif
        }
示例#4
0
        public virtual object Create(Object parent, Object configContextObj, XmlNode section)
        {
            // if called through client config don't even load HttpRuntime
            if (!HandlerBase.IsServerConfiguration(configContextObj))
            {
                return(null);
            }

            HttpConfigurationContext configContext = (HttpConfigurationContext)configContextObj;

            if (HandlerBase.IsPathAtAppLevel(configContext.VirtualPath) == PathLevel.BelowApp)
            {
                throw new ConfigurationException(
                          HttpRuntime.FormatResourceString(SR.Cannot_specify_below_app_level, section.Name),
                          section);
            }

            HandlerBase.CheckForChildNodes(section);
            CodeAccessSecurityValues oRet = new CodeAccessSecurityValues();

            XmlNode oAttribute = section.Attributes.RemoveNamedItem("level");

            if (oAttribute != null)
            {
                oRet.level = oAttribute.Value;
            }
            else
            {
                oRet.level = (parent != null ? ((CodeAccessSecurityValues)parent).level : "");
            }

            oAttribute = section.Attributes.RemoveNamedItem("originUrl");
            if (oAttribute != null)
            {
                oRet.url = oAttribute.Value;
            }
            else
            {
                oRet.url = (parent != null ? ((CodeAccessSecurityValues)parent).url : "");
            }

            HandlerBase.CheckForUnrecognizedAttributes(section);

            oRet.filename   = ConfigurationException.GetXmlNodeFilename(section);
            oRet.lineNumber = ConfigurationException.GetXmlNodeLineNumber(section);

            return(oRet);
        }
        static void AppendLines(ArrayList setlist, String text, XmlNode node)
        {
            int lineNumber = ConfigurationException.GetXmlNodeLineNumber(node);
            int textpos;

            textpos = 0;

            for (;;)
            {
                Match match;

                if ((match = wsRegex.Match(text, textpos)).Success)
                {
                    lineNumber += LineCount(text, textpos, match.Index + match.Length);
                    textpos     = match.Index + match.Length;
                }

                if (textpos == text.Length)
                {
                    break;
                }

                if ((match = lineRegex.Match(text, textpos)).Success)
                {
                    setlist.Add(new CapabilitiesAssignment(match.Groups["var"].Value,
                                                           new CapabilitiesPattern(match.Groups["pat"].Value)));

                    lineNumber += LineCount(text, textpos, match.Index + match.Length);
                    textpos     = match.Index + match.Length;
                }
                else
                {
                    match = errRegex.Match(text, textpos);

                    throw new ConfigurationException(
                              HttpRuntime.FormatResourceString(SR.Problem_reading_caps_config, match.ToString()),
                              ConfigurationException.GetXmlNodeFilename(node),
                              lineNumber);
                }
            }
        }
        //
        // ResolveFiles - parse files referenced with <file src="" />
        //
        static void ResolveFiles(ParseState parseState, object configurationContext)
        {
            //
            // 1) get the directory of the configuration file currently being parsed
            //

            HttpConfigurationContext httpConfigurationContext = (HttpConfigurationContext)configurationContext;
            string configurationDirectory = null;
            bool   useAssert = false;

            //
            // Only assert to read cap files when parsing machine.config
            // (allow device updates to work in restricted trust levels).
            //
            // Machine.config can be securely identified by the context being
            // an HttpConfigurationContext with null path.
            //
            try {
                if (httpConfigurationContext.VirtualPath == null)
                {
                    useAssert = true;
                    // we need to assert here to get the file path from ConfigurationException
                    FileIOPermission fiop = new FileIOPermission(PermissionState.None);
                    fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
                    fiop.Assert();
                }

                Pair    pair0        = (Pair)parseState.FileList[0];
                XmlNode srcAttribute = (XmlNode)pair0.Second;
                configurationDirectory = Path.GetDirectoryName(ConfigurationException.GetXmlNodeFilename(srcAttribute));
            }
            finally {
                if (useAssert)
                {
                    CodeAccessPermission.RevertAssert();
                }
            }

            //
            // 2) iterate through list of referenced files, builing rule lists for each
            //
            foreach (Pair pair in parseState.FileList)
            {
                string srcFilename  = (string)pair.First;
                string fullFilename = Path.Combine(configurationDirectory, srcFilename);

                XmlNode section;
                try {
                    if (useAssert)
                    {
                        InternalSecurityPermissions.FileReadAccess(fullFilename).Assert();
                    }

                    Exception fcmException = null;

                    try {
                        HttpConfigurationSystem.AddFileDependency(fullFilename);
                    }
                    catch (Exception e) {
                        fcmException = e;
                    }

                    ConfigXmlDocument configDoc = new ConfigXmlDocument();

                    try {
                        configDoc.Load(fullFilename);
                        section = configDoc.DocumentElement;
                    }
                    catch (Exception e) {
                        throw new ConfigurationException(HttpRuntime.FormatResourceString(SR.Error_loading_XML_file, fullFilename, e.Message),
                                                         e, (XmlNode)pair.Second);
                    }

                    if (fcmException != null)
                    {
                        throw fcmException;
                    }
                }
                finally {
                    if (useAssert)
                    {
                        // Cannot apply next FileReadAccess PermissionSet unless
                        // current set is explicitly reverted.  Also minimizes
                        // granted permissions.
                        CodeAccessPermission.RevertAssert();
                    }
                }

                if (section.Name != parseState.SectionName)
                {
                    throw new ConfigurationException(HttpRuntime.FormatResourceString(SR.Capability_file_root_element, parseState.SectionName),
                                                     section);
                }

                HandlerBase.CheckForUnrecognizedAttributes(section);

                ArrayList sublist = RuleListFromElement(parseState, section, true);

                if (sublist.Count > 0)
                {
                    parseState.RuleList.Add(new CapabilitiesSection(CapabilitiesRule.Filter, null, null, sublist));
                }
            }
        }
            private static void ProcessCompilersElement(CompilationConfiguration result, XmlNode node)
            {
                // reject attributes
                HandlerBase.CheckForUnrecognizedAttributes(node);

                string configFile = ConfigurationException.GetXmlNodeFilename(node);

                foreach (XmlNode child in node.ChildNodes)
                {
                    // skip whitespace and comments
                    // reject nonelements
                    if (HandlerBase.IsIgnorableAlsoCheckForNonElement(child))
                    {
                        continue;
                    }

                    if (child.Name != "compiler")
                    {
                        HandlerBase.ThrowUnrecognizedElement(child);
                    }

                    string languages = String.Empty;
                    HandlerBase.GetAndRemoveStringAttribute(child, "language", ref languages);
                    string extensions = String.Empty;
                    HandlerBase.GetAndRemoveStringAttribute(child, "extension", ref extensions);
                    string compilerTypeName = null;
                    HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "type", ref compilerTypeName);

                    // Create a CompilerParameters for this compiler.
                    CompilerParameters compilParams = new CompilerParameters();

                    int warningLevel = 0;
                    if (HandlerBase.GetAndRemoveNonNegativeIntegerAttribute(child, "warningLevel", ref warningLevel) != null)
                    {
                        compilParams.WarningLevel = warningLevel;

                        // Need to be false if the warning level is 0
                        compilParams.TreatWarningsAsErrors = (warningLevel > 0);
                    }
                    string compilerOptions = null;
                    if (HandlerBase.GetAndRemoveStringAttribute(child, "compilerOptions", ref compilerOptions) != null)
                    {
                        compilParams.CompilerOptions = compilerOptions;
                    }

                    HandlerBase.CheckForUnrecognizedAttributes(child);
                    HandlerBase.CheckForChildNodes(child);

                    // Create a CompilerInfo structure for this compiler
                    int          configFileLine = ConfigurationException.GetXmlNodeLineNumber(child);
                    CompilerInfo compilInfo     = new CompilerInfo(compilParams, compilerTypeName, configFile, configFileLine);

                    if (result._compilerLanguages == null)
                    {
                        result._compilerLanguages  = new Hashtable(SymbolHashCodeProvider.Default, SymbolEqualComparer.Default);
                        result._compilerExtensions = new Hashtable(SymbolHashCodeProvider.Default, SymbolEqualComparer.Default);
                    }

                    // Parse the semicolon separated lists
                    string[] languageList  = languages.Split(s_fieldSeparators);
                    string[] extensionList = extensions.Split(s_fieldSeparators);

                    foreach (string language in languageList)
                    {
                        result._compilerLanguages[language] = compilInfo;
                    }

                    foreach (string extension in extensionList)
                    {
                        result._compilerExtensions[extension] = compilInfo;
                    }
                }
            }
            private static void ProcessAssembliesElement(CompilationConfiguration result, XmlNode node)
            {
                // reject attributes
                HandlerBase.CheckForUnrecognizedAttributes(node);

                string configFile = ConfigurationException.GetXmlNodeFilename(node);

                Hashtable addEntries    = null;
                Hashtable removeEntries = null;
                bool      hasClear      = false;

                foreach (XmlNode child in node.ChildNodes)
                {
                    // skip whitespace and comments
                    // reject nonelements
                    if (HandlerBase.IsIgnorableAlsoCheckForNonElement(child))
                    {
                        continue;
                    }

                    // handle <add>, <remove>, <clear> tags

                    if (child.Name == "add")
                    {
                        string assemblyName = GetAssembly(child);

                        // Check for duplicate lines (ASURT 93151)
                        if (addEntries == null)
                        {
                            addEntries = new Hashtable(new CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture), new CaseInsensitiveComparer(CultureInfo.InvariantCulture));
                        }
                        if (addEntries.ContainsKey(assemblyName))
                        {
                            HandlerBase.ThrowDuplicateLineException(child);
                        }
                        addEntries[assemblyName] = null;

                        if (result._assemblies == null)
                        {
                            result._assemblies = new Hashtable(new CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture), new CaseInsensitiveComparer(CultureInfo.InvariantCulture));
                        }

                        // if key already exists then we might have already loaded it
                        if (result._assemblies.ContainsKey(assemblyName) == false)
                        {
                            if (assemblyName == "*")
                            {
                                AddAllAssembliesFromAppDomainBinDirectory(result, child);
                            }
                            else
                            {
                                // Remember the config file location info, in case an error
                                // occurs later when we try to load the assembly (ASURT 72183)
                                int configFileLine = ConfigurationException.GetXmlNodeLineNumber(child);
                                result._assemblies[assemblyName] = new object[]
                                { configFile, configFileLine, false /*starDirective*/ };
                            }
                        }
                    }
                    else if (child.Name == "remove")
                    {
                        string assemblyName = GetAssembly(child);

                        // Check for duplicate lines (ASURT 93151)
                        if (removeEntries == null)
                        {
                            removeEntries = new Hashtable(new CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture), new CaseInsensitiveComparer(CultureInfo.InvariantCulture));
                        }
                        if (removeEntries.ContainsKey(assemblyName))
                        {
                            HandlerBase.ThrowDuplicateLineException(child);
                        }
                        removeEntries[assemblyName] = null;

                        if (result._assemblies != null)
                        {
                            // If it's a '*' remove everything
                            if (assemblyName == "*")
                            {
                                result._assemblies.Clear();
                            }
                            else
                            {
                                // Otherwise, just remove the one assembly (if present)
                                result._assemblies.Remove(assemblyName);
                            }
                        }
                    }
                    else if (child.Name == "clear")
                    {
                        // Check for duplicate lines (ASURT 93151)
                        if (hasClear)
                        {
                            HandlerBase.ThrowDuplicateLineException(child);
                        }
                        hasClear = true;

                        HandlerBase.CheckForUnrecognizedAttributes(child);
                        HandlerBase.CheckForChildNodes(child);
                        if (result._assemblies != null)
                        {
                            result._assemblies.Clear();
                        }
                    }
                    else
                    {
                        HandlerBase.ThrowUnrecognizedElement(child);
                    }
                }
            }