// FIXME: imperative PermitOnly isn't supported public override object GetEntity( Uri absoluteUri, string role, Type ofObjectToReturn) { if (SecurityManager.SecurityEnabled) { // in case the security manager was switched after the constructor was called if (permissionSet == null) { throw new SecurityException(Locale.GetText( "Security Manager wasn't active when instance was created.")); } permissionSet.PermitOnly(); } return(resolver.GetEntity(absoluteUri, role, ofObjectToReturn)); }
/// <summary> /// Create a registry key tree using self-assigned permissions. /// </summary> /// <param name="subKeyTree">The registry key tree to be created.</param> /// <param name="state">Permission state to apply to local permission set.</param> /// <returns>Success or failure of key creation.</returns> private static bool CreateRegistryKey(string subKeyTree, PermissionState state) { // Create empty permission set. var permissionSet = new PermissionSet(null); // Add RegistryPermission to permission set with passed state value. permissionSet.AddPermission(new RegistryPermission(state)); // Ensure that only the above permissions are applied, regardless // of permissions assigned to executing user account. permissionSet.PermitOnly(); try { // Create registry key. var key = Registry.CurrentUser.CreateSubKey(subKeyTree); // Check that result is valid. if (key != null) { // Output creation message. Logging.Log($"Created registry key: {key.Name}."); return(true); } } catch (System.Security.SecurityException exception) { // Log potential security exceptions. Logging.Log(exception); } catch (Exception exception) { // Log any inexplicit exceptions. Logging.Log(exception, false); } return(false); }
/// <summary> /// Delete a registry parent key (and all child keys). /// </summary> /// <param name="parentKey">Parent key to delete.</param> /// <param name="state">Permission state to apply to local permission set.</param> /// <returns>Success or failure of key deletion.</returns> private static bool DeleteRegistryKey(string parentKey, PermissionState state) { // Create empty permission set. var permissionSet = new PermissionSet(null); // Add RegistryPermission to permission set with passed state value. permissionSet.AddPermission(new RegistryPermission(state)); // Ensure that only the above permissions are applied, regardless // of permissions assigned to executing user account. permissionSet.PermitOnly(); try { // Delete the provided registry key (and child keys). Registry.CurrentUser.DeleteSubKeyTree(parentKey); // Output confirmation message of deletion. Logging.Log($"Deleted registry key (with children): {parentKey}."); return(true); } catch (System.Security.SecurityException exception) { // Log potential security exceptions. Logging.Log(exception); } catch (Exception exception) { // Log any inexplicit exceptions. Logging.Log(exception, false); } return(false); }
private void DownloadCipherValue(CipherData cipherData, out Stream inputStream, out Stream decInputStream, out WebResponse response) { // maybe a network stream, make sure we allow just what is needed!! PermissionSet ps = SecurityManager.GetStandardSandbox(m_evidence); ps.PermitOnly(); WebRequest request = WebRequest.Create(cipherData.CipherReference.Uri); if (request == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), cipherData.CipherReference.Uri); } response = request.GetResponse(); if (response == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), cipherData.CipherReference.Uri); } inputStream = response.GetResponseStream(); if (inputStream == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), cipherData.CipherReference.Uri); } TransformChain tc = cipherData.CipherReference.TransformChain; decInputStream = tc.TransformToOctetStream(inputStream, m_xmlResolver, cipherData.CipherReference.Uri); }
public void Run(ScriptCode code, CompilerOutputDelegate cod, PermissionSet permissionSet) { var resultAssembly = this.Compile(code.SourceCode, cod).CompiledAssembly; if (resultAssembly != null) { if (permissionSet != null) { permissionSet.PermitOnly(); } //// run script foreach (var item in code.StartUpList.OrderBy(row => row.order)) { if (resultAssembly.GetType(item.ClassName) == null || resultAssembly.GetType(item.ClassName).GetMethod(item.MethordName) == null) { throw new Exception(string.Format("没有找到公共的{0}.{0}", item.ClassName, item.MethordName)); } MethodInfo methordInfo = resultAssembly.GetType(item.ClassName).GetMethod(item.MethordName); methordInfo.Invoke(item.Instance, item.MethordParameters); } if (permissionSet != null) { CodeAccessPermission.RevertPermitOnly(); } } }
public static void InsertLatestStockPrice(string symbol) { try { PermissionSet perms = new PermissionSet(PermissionState.None); string url = "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ov"; WebPermission webPerm = new WebPermission(NetworkAccess.Connect, url); perms.AddPermission(webPerm); SqlClientPermission sqlPerm = new SqlClientPermission( PermissionState.None); sqlPerm.Add("context connection=true", "", KeyRestrictionBehavior.AllowOnly); perms.AddPermission(sqlPerm); perms.PermitOnly(); string[] data = HttpFileReader.ReadFile(url); string[] cols = data[0].Split(new char[] { ',' }); string date = cols[2].Substring(1, cols[2].Length - 2); string time = cols[3].Substring(1, cols[3].Length - 2); DateTime tradetime = DateTime.Parse(date + " " + time); double price = Double.Parse(cols[1]); double change = Double.Parse(cols[4]); SqlDouble openprice = cols[5] == "N/A" ? SqlDouble.Null : SqlDouble.Parse(cols[5]); int volume = Int32.Parse(cols[6]); using (SqlConnection cn = new SqlConnection("context connection=true")) { cn.Open(); string cmdStr = "INSERT INTO StockPrices VALUES (@symbol, @price, @tradetime, @change, @openprice, @volume)"; SqlCommand cmd = new SqlCommand(cmdStr, cn); cmd.Parameters.AddWithValue("@symbol", symbol); cmd.Parameters.AddWithValue("@price", price); cmd.Parameters.AddWithValue("@tradetime", tradetime); cmd.Parameters.AddWithValue("@change", change); cmd.Parameters.AddWithValue("@openprice", openprice); cmd.Parameters.AddWithValue("@volume", volume); cmd.ExecuteNonQuery(); } } catch (Exception e) { SqlPipe pipe = SqlContext.Pipe; pipe.Send(e.Message); } }
internal SrgsRule[] OnInit(string method, object[] parameters, string onInitParameters, out Exception exceptionThrown) { exceptionThrown = null; try { if (!string.IsNullOrEmpty(onInitParameters)) { parameters = MatchInitParameters(method, onInitParameters, _rule, _rule); } Type[] array = new Type[(parameters != null) ? parameters.Length : 0]; if (parameters != null) { for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].GetType(); } } MethodInfo method2 = _grammarType.GetMethod(method, array); if (method2 == null) { throw new InvalidOperationException(SR.Get(SRID.ArgumentMismatch)); } SrgsRule[] result = null; if (method2 != null) { _internetPermissionSet.PermitOnly(); result = (SrgsRule[])method2.Invoke(_grammar, parameters); } return(result); } catch (Exception ex) { Exception ex2 = exceptionThrown = ex; return(null); } }
static void ExecuteInSandbox(PermissionSet permissionSet, Action action) { permissionSet.PermitOnly(); try { action(); } catch (Exception e) { Console.WriteLine(e.GetType().ToString() + ": " + e.Message); } finally { CodeAccessPermission.RevertPermitOnly(); } }
public static void Main() { PermissionSet perms = new PermissionSet(null); perms.AddPermission(new UIPermission(PermissionState.Unrestricted)); perms.AddPermission(new RegistryPermission(PermissionState.None)); perms.PermitOnly(); try { RegistryKey key = Registry.CurrentUser.CreateSubKey("MyCompany\\Applications"); Console.WriteLine("Registry key: {0}", key.Name); } catch (SecurityException e) { Console.WriteLine("Security Exception:\n\n{0}", e.Message); } }
void RunCode() { try { // Deny a permission. KeyContainerPermission kCP1 = new KeyContainerPermission( KeyContainerPermissionFlags.Decrypt); kCP1.Deny(); // Demand the denied permission and display the // exception properties. Display("Demanding a denied permission. \n\n"); DemandDeniedPermission(); Display("************************************************\n"); CodeAccessPermission.RevertDeny(); // Demand the permission refused in the // assembly-level attribute. Display("Demanding a refused permission. \n\n"); DemandRefusedPermission(); Display("************************************************\n"); // Demand the permission implicitly refused through a // PermitOnly attribute. Permit only the permission that // will cause the failure and the security permissions // necessary to display the results of the failure. PermissionSet permitOnly = new PermissionSet( PermissionState.None); permitOnly.AddPermission(new KeyContainerPermission( KeyContainerPermissionFlags.Import)); permitOnly.AddPermission(new SecurityPermission( SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.SerializationFormatter)); permitOnly.PermitOnly(); Display("Demanding an implicitly refused permission. \n\n"); DemandPermitOnly(); } catch (Exception sE) { Display("************************************************\n"); //<Snippet17> Display("Displaying an exception using the ToString method: "); Display(sE.ToString()); //</Snippet17> } }
/// <summary> /// TestAssert /// </summary> /// <param name="toPermitOnly"></param> /// <param name="toDemand"></param> /// <returns>true if assert stopped demand; false if assert didn't stop demand</returns> internal static bool DemandSuccedsAfterPermitOnly(PermissionSet toPermitOnly, PermissionSet toDemand) { // assert full trust first new PermissionSet(PermissionState.Unrestricted).Assert(); // permit only given permission set toPermitOnly.PermitOnly(); try { TransparentSecurityHelper.Demand(toDemand); return(true); } catch (SecurityException) { return(false); } }
public void CanChangeConnectionSettingsOnClientPermission() { MySqlConnection dummyconn = new MySqlConnection(); PermissionSet permissionsSet = new PermissionSet(PermissionState.None); MySqlClientPermission permission = new MySqlClientPermission(PermissionState.None); // Allow only server localhost, any database, only with root user permission.Add("server=localhost;", "database=; user id=root;", KeyRestrictionBehavior.PreventUsage); permissionsSet.AddPermission(permission); permissionsSet.PermitOnly(); dummyconn.ConnectionString = "server=localhost; user id=test;includesecurityasserts=true;"; dummyconn.Open(); if (dummyconn.State == ConnectionState.Open) { dummyconn.Close(); } }
private static void UseCAS() { ColoredWriteLine("Testing CAS", ConsoleColor.Cyan); PermissionSet ps = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted); ps.Demand(); Console.WriteLine("PermissionSet.Demand succeeded"); ps.Assert(); Console.WriteLine("PermissionSet.Assert succeeded"); try { ps.PermitOnly(); Console.WriteLine("PermissionSet.PermitOnly succeeded"); } catch (PlatformNotSupportedException) { ColoredWriteLine("Caught platform not supported exception", ConsoleColor.Yellow); } Console.WriteLine(); }
private object GetRuntimeObjectWithRestrictedPermissions(ConfigurationSection section) { // Run configuration section handlers as if user code was on the stack bool revertPermitOnly = false; try { PermissionSet permissionSet = GetRestrictedPermissions(); if (permissionSet != null) { permissionSet.PermitOnly(); revertPermitOnly = true; } return(section.GetRuntimeObject()); } finally { if (revertPermitOnly) { CodeAccessPermission.RevertPermitOnly(); } } }
private void InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) { bool flag = false; try { PermissionSet restrictedPermissions = configRecord.GetRestrictedPermissions(); if (restrictedPermissions != null) { restrictedPermissions.PermitOnly(); flag = true; } this.Init(configRecord, factoryRecord); } finally { if (flag) { CodeAccessPermission.RevertPermitOnly(); } } }
private void InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) { // Run configuration section handlers as if user code was on the stack bool revertPermitOnly = false; try { PermissionSet permissionSet = configRecord.GetRestrictedPermissions(); if (permissionSet != null) { permissionSet.PermitOnly(); revertPermitOnly = true; } Init(configRecord, factoryRecord); } finally { if (revertPermitOnly) { CodeAccessPermission.RevertPermitOnly(); } } }
/// <summary> /// Invokes the given callback using the specified permissionset. /// </summary> // [SecurityTreatAsSafe, SecurityCritical] public void PartialTrustInvoke(string permissionSetName, ThreadStart callback) { PermissionSet ps = null; ps = GetNamedPermissionSet(permissionSetName); if (ps == null && throwOnUnknownPermissionSet) { throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName, string.Format("unknown PermissionSet name '{0}'", permissionSetName)); } if (!IsFullTrust(ps)) { ps.PermitOnly(); callback(); CodeAccessPermission.RevertPermitOnly(); } else { callback(); } }
private object CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentConfig, ConfigXmlReader reader) { object obj2; bool flag = false; try { PermissionSet restrictedPermissions = configRecord.GetRestrictedPermissions(); if (restrictedPermissions != null) { restrictedPermissions.PermitOnly(); flag = true; } obj2 = this.CreateSectionImpl(configRecord, factoryRecord, sectionRecord, parentConfig, reader); } finally { if (flag) { CodeAccessPermission.RevertPermitOnly(); } } return(obj2); }
private object GetRuntimeObjectWithRestrictedPermissions(ConfigurationSection section) { object runtimeObject; bool flag = false; try { PermissionSet restrictedPermissions = base.GetRestrictedPermissions(); if (restrictedPermissions != null) { restrictedPermissions.PermitOnly(); flag = true; } runtimeObject = section.GetRuntimeObject(); } finally { if (flag) { CodeAccessPermission.RevertPermitOnly(); } } return(runtimeObject); }
private object CreateSectionWithRestrictedPermissions( RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentConfig, ConfigXmlReader reader) { // run configuration section handlers as if user code was on the stack bool revertPermitOnly = false; try { PermissionSet permissionSet = configRecord.GetRestrictedPermissions(); if (permissionSet != null) { permissionSet.PermitOnly(); revertPermitOnly = true; } return(CreateSectionImpl(configRecord, factoryRecord, sectionRecord, parentConfig, reader)); } finally { if (revertPermitOnly) { CodeAccessPermission.RevertPermitOnly(); } } }
public byte[] ValidateEntryAssembly(byte[] blackboxData) { //Create permissions var permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Assembly.GetExecutingAssembly().Location)); permissions.AddPermission(new FileIOPermission( FileIOPermissionAccess.AllAccess | FileIOPermissionAccess.PathDiscovery, Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Log.OutputFile))); Log.Write("AssemblyLoader::ValidateEntryAssembly() - data length: " + ((blackboxData != null) ? blackboxData.Length : -1).ToString()); //Gather machine information List <string> macs = null, edids = null, disks = null; if (blackboxData != null) { Fingerprint.GatherAll(out macs, out edids, out disks); } try { permissions.PermitOnly(); Assembly assembly; if (blackboxData != null) { assembly = Assembly.Load(blackboxData, null); _latest = assembly; } else { assembly = _latest; } Log.Write("AssemblyLoader::ValidateEntryAssembly() loaded assembly: " + ((assembly != null) ? assembly.GetType().ToString() : "null")); var validatorType = assembly.GetType("Allegiance.CommunitySecuritySystem.Blackbox.Validator"); var machineInfoType = assembly.GetType("Allegiance.CommunitySecuritySystem.Blackbox.MachineInformation"); var deviceInfoType = assembly.GetType("Allegiance.CommunitySecuritySystem.Blackbox.DeviceInfo"); var deviceTypeType = assembly.GetType("Allegiance.CommunitySecuritySystem.Blackbox.DeviceType"); var machineInfo = Activator.CreateInstance(machineInfoType); Log.Write("AssemblyLoader::ValidateEntryAssembly() machine info created."); //Fill MachineInfo if (macs != null && edids != null && disks != null) { AppendDeviceInfo(macs, machineInfo, "Network", machineInfoType, deviceInfoType, deviceTypeType); AppendDeviceInfo(edids, machineInfo, "EDID", machineInfoType, deviceInfoType, deviceTypeType); AppendDeviceInfo(disks, machineInfo, "HardDisk", machineInfoType, deviceInfoType, deviceTypeType); } Log.Write("AssemblyLoader::ValidateEntryAssembly() calling checkin."); //Perform initial check in var method = validatorType.GetMethod("Check", BindingFlags.Static | BindingFlags.Public); return(method.Invoke(null, new object[] { machineInfo }) as byte[]); } finally { //Revert permission changes SecurityPermission.RevertPermitOnly(); Log.Write("AssemblyLoader::ValidateEntryAssembly() calling checkin."); } }
/// <summary> /// Load a project from a file /// </summary> /// <param name="stm">The stream</param> /// <param name="fileName">The filename to use (can be null)</param> /// <param name="verifyVersion">Set true to verify the version being opened match this canape</param> /// <param name="secure">Attemps to make the load secure, not likely to succeed</param> public static void Load(Stream stm, string fileName, bool verifyVersion, bool secure) { // If an empty stream if (stm.Length == 0) { New(); } else { Version ver = ReadFileHeader(stm); bool compressed = true; if (verifyVersion) { if (ver.CompareTo(GeneralUtils.GetCanapeVersion()) != 0) { throw new InvalidVersionException(ver); } } if (stm.ReadByte() == 0x1F) { compressed = true; } else { compressed = false; } stm.Position = stm.Position - 1; using (Stream inStream = compressed ? new GZipStream(stm, CompressionMode.Decompress, false) : stm) { BinaryFormatter formatter = CreateFormatter(ver, secure); CANAPEProject newProject = null; // Note that all this is going to do is prevent anything during // direct load of objects and scripts, it won't do anything against anything else if (secure) { try { PermissionSet ps = new PermissionSet(PermissionState.None); ps.PermitOnly(); newProject = (CANAPEProject)formatter.UnsafeDeserialize(inStream, null); } finally { CodeAccessPermission.RevertPermitOnly(); } } else { newProject = (CANAPEProject)formatter.Deserialize(inStream); } newProject._fileName = fileName; newProject._globalMeta = new MetaDictionary(); currentProject = newProject; if (ProjectLoaded != null) { ProjectLoaded.Invoke(currentProject, new EventArgs()); } } } }
public static void Main() { // Try to access resources using the permissions currently available. AttemptAccess("Default permissions"); // Create a permission set that allows read access to the TEMP // environment variable and read, write, and append access to SomeFile PermissionSet ps = new PermissionSet(PermissionState.None); ps.AddPermission( new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP")); ps.AddPermission( new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, Path.GetFullPath("SomeFile"))); // Use caution in asserting permissions in publicly callable code without // any kind of check on the caller. There is a danger of the assert being // used to exploit a downstream caller by stopping its security check, // allowing the malicious code access to unauthorized resources. // Stop security checks at this point in the stack walk // for the specified permissions ps.Assert(); // Try to access resources using the permissions we've just asserted. AttemptAccess("Assert permissions"); // Remove this stack frame's Assert CodeAccessPermission.RevertAssert(); // Deny access to the resources we specify ps.Deny(); // Try to access resources using the permissions we've just denied. AttemptAccess("Deny permissions"); // Remove this stack frame's Deny so we're back to default permissions. CodeAccessPermission.RevertDeny(); // Make the permissions indicate the only things that we're allowed to do. ps.PermitOnly(); // Try to access resources using only the permissions we've just permitted. AttemptAccess("PermitOnly permissions"); // Remove this stack frame's PermitOnly so we're back to default permissions. CodeAccessPermission.RevertPermitOnly(); // Remove the FileIOPermissions from the permission set ps.RemovePermission(typeof(FileIOPermission)); // Try to access resources using only the Environment permissions. ps.PermitOnly(); AttemptAccess("PermitOnly without FileIOPermission permissions"); CodeAccessPermission.RevertPermitOnly(); // Remove the EnvironmentPermission from the permission set ps.RemovePermission(typeof(EnvironmentPermission)); // Try to access resources using no permissions. ps.PermitOnly(); AttemptAccess("PermitOnly without any permissions"); CodeAccessPermission.RevertPermitOnly(); // Show how to use Demand/Assert to improve performance CopyFile(".\\Permissions.exe", ".\\Permissions.copy.exe"); // Delete .exe copy File.Delete(".\\Permissions.copy.exe"); }
/// <summary> /// Perform call to "Waits()" on given ant. /// </summary> /// <param name="ant">ant</param> public static void Waits(CoreAnt ant) { AreaChanged( null, new AreaChangeEventArgs(ant.colony.Player, Area.Waits)); playerRights.PermitOnly(); ant.NimmBefehleEntgegen = true; try { ant.WartetBase(); } catch (Exception ex) { throw new AiException(string.Format("{0}: KI-Fehler in der Wartet()-Methode", ant.colony.Player.Guid), ex); } ant.NimmBefehleEntgegen = false; AreaChanged( null, new AreaChangeEventArgs(null, Area.Unknown)); }
public static void GetSalesForNames(SqlString filename) { try { PermissionSet perms = new PermissionSet(PermissionState.None); // Ensure that only correct file can be accessed through this method FileIOPermission ioPerm = new FileIOPermission( FileIOPermissionAccess.Read, @"C:\names.txt"); perms.AddPermission(ioPerm); // Permit access to SQL Server data SqlClientPermission sqlPerm = new SqlClientPermission( PermissionState.None); sqlPerm.Add("context connection=true", "", KeyRestrictionBehavior.AllowOnly); perms.AddPermission(sqlPerm); perms.PermitOnly(); // Get the names from the text file as a string array string[] names = FileReader.ReadFile(filename.ToString()); // Build SQL statement StringBuilder sb = new StringBuilder(); sb.Append(@"SELECT emp.EmployeeID, sp.SalesYTD + sp.SalesLastYear AS RecentSales FROM Sales.SalesPerson sp INNER JOIN HumanResources.Employee emp ON emp.EmployeeID = sp.SalesPersonID WHERE sp.SalesPersonID IN ( SELECT emp.EmployeeID FROM HumanResources.Employee emp INNER JOIN Person.Contact c ON c.ContactID = emp.ContactID WHERE c.FirstName + ' ' + c.MiddleName + ' ' + c.LastName IN ("); // Concatenate array into single string for WHERE clause foreach (string name in names) { sb.Append("'"); sb.Append(name); sb.Append("', "); } sb.Remove(sb.Length - 2, 2); sb.Append("))"); // Execute the SQL statement and get back a SqlResultSet using (SqlConnection cn = new SqlConnection( "context connection=true")) { cn.Open(); SqlCommand cmd = new SqlCommand(sb.ToString(), cn); SqlDataReader dr = cmd.ExecuteReader(); // Send success message to SQL Server and return SqlDataReader SqlPipe pipe = SqlContext.Pipe; pipe.Send(dr); pipe.Send("Command(s) completed successfully."); cn.Close(); } } catch (Exception e) { SqlPipe pipe = SqlContext.Pipe; pipe.Send(e.Message); pipe.Send(e.StackTrace); pipe.Send("Error executing assembly"); } }
private void CreateAvailableWebPartDescriptions() { if (this._availableWebPartDescriptions == null) { if ((base.WebPartManager == null) || string.IsNullOrEmpty(this._importedPartDescription)) { this._availableWebPartDescriptions = new WebPartDescriptionCollection(); } else { PermissionSet set = new PermissionSet(PermissionState.None); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); set.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal)); set.PermitOnly(); bool flag = true; string str = null; string description = null; string imageUrl = null; try { try { using (StringReader reader = new StringReader(this._importedPartDescription)) { using (XmlTextReader reader2 = new XmlTextReader(reader)) { if (reader2 == null) { goto Label_02F7; } reader2.MoveToContent(); reader2.MoveToContent(); reader2.ReadStartElement("webParts"); reader2.ReadStartElement("webPart"); reader2.ReadStartElement("metaData"); string str4 = null; string path = null; while (reader2.Name != "type") { reader2.Skip(); if (reader2.EOF) { throw new EndOfStreamException(); } } if (reader2.Name == "type") { str4 = reader2.GetAttribute("name"); path = reader2.GetAttribute("src"); } bool isShared = base.WebPartManager.Personalization.Scope == PersonalizationScope.Shared; if (!string.IsNullOrEmpty(str4)) { PermissionSet set2 = new PermissionSet(PermissionState.None); set2.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); set2.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium)); CodeAccessPermission.RevertPermitOnly(); flag = false; set2.PermitOnly(); flag = true; Type type = WebPartUtil.DeserializeType(str4, true); CodeAccessPermission.RevertPermitOnly(); flag = false; set.PermitOnly(); flag = true; if (!base.WebPartManager.IsAuthorized(type, null, null, isShared)) { this._importErrorMessage = System.Web.SR.GetString("WebPartManager_ForbiddenType"); } else { if (type.IsSubclassOf(typeof(WebPart)) || type.IsSubclassOf(typeof(Control))) { goto Label_02DD; } this._importErrorMessage = System.Web.SR.GetString("WebPartManager_TypeMustDeriveFromControl"); } } else { if (base.WebPartManager.IsAuthorized(typeof(UserControl), path, null, isShared)) { goto Label_02DD; } this._importErrorMessage = System.Web.SR.GetString("WebPartManager_ForbiddenType"); } return; Label_021E: reader2.Read(); Label_0226: if (!reader2.EOF && ((reader2.NodeType != XmlNodeType.Element) || !(reader2.Name == "property"))) { goto Label_021E; } if (reader2.EOF) { goto Label_02F7; } string attribute = reader2.GetAttribute("name"); if (attribute == "Title") { str = reader2.ReadElementString(); } else if (attribute == "Description") { description = reader2.ReadElementString(); } else if (attribute == "CatalogIconImageUrl") { string s = reader2.ReadElementString().Trim(); if (!CrossSiteScriptingValidation.IsDangerousUrl(s)) { imageUrl = s; } } else { reader2.Read(); goto Label_02DD; } if (((str != null) && (description != null)) && (imageUrl != null)) { goto Label_02F7; } reader2.Read(); Label_02DD: if (!reader2.EOF) { goto Label_0226; } } Label_02F7: if (string.IsNullOrEmpty(str)) { str = System.Web.SR.GetString("Part_Untitled"); } this._availableWebPartDescriptions = new WebPartDescriptionCollection(new WebPartDescription[] { new WebPartDescription("ImportedWebPart", str, description, imageUrl) }); } } catch (XmlException) { this._importErrorMessage = System.Web.SR.GetString("WebPartManager_ImportInvalidFormat"); } catch { this._importErrorMessage = !string.IsNullOrEmpty(this._importErrorMessage) ? this._importErrorMessage : System.Web.SR.GetString("WebPart_DefaultImportErrorMessage"); } finally { if (flag) { CodeAccessPermission.RevertPermitOnly(); } } } catch { throw; } } } }
/// <include file='doc\XmlSecureResolver.uex' path='docs/doc[@for="XmlSecureResolver.GetEntity"]/*' /> public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { permissionSet.PermitOnly(); return(resolver.GetEntity(absoluteUri, role, ofObjectToReturn)); }
private object EvaluateRecursive(IConfigurationSectionHandler factory, object config, string [] keys, int iKey, XmlTextReader reader) { string name = keys[iKey]; TraceVerbose(" EvaluateRecursive " + iKey + " " + name); int depth = reader.Depth; while (reader.Read() && reader.NodeType != XmlNodeType.Element) { ; } while (reader.Depth == depth + 1) { TraceVerbose(" EvaluateRecursive " + iKey + " " + name + " Name:" + reader.Name); if (reader.Name == name) { if (iKey < keys.Length - 1) { config = EvaluateRecursive(factory, config, keys, iKey + 1, reader); } else { TraceVerbose(" EvaluateRecursive " + iKey + " calling Create()"); Debug.Assert(iKey == keys.Length - 1); PermissionSet permissionSet = CreatePermissionSetFromLocation(_filename); permissionSet.PermitOnly(); try { // // Call configuration section handler // // - try-catch is necessary to insulate config system from exceptions in user config handlers. // - bubble ConfigurationExceptions & XmlException // - wrap all others in ConfigurationException // int line = reader.LineNumber; try { ConfigXmlDocument doc = new ConfigXmlDocument(); XmlNode section = doc.ReadConfigNode(_filename, reader); config = factory.Create(config, null, section); } catch (ConfigurationException) { throw; } catch (XmlException) { throw; } catch (Exception ex) { throw new ConfigurationException( SR.GetString(SR.Exception_in_config_section_handler), ex, _filename, line); } } finally { CodeAccessPermission.RevertPermitOnly(); } } continue; } StrictSkipToNextElement(reader); } return(config); }
private void CreateAvailableWebPartDescriptions() { if (_availableWebPartDescriptions != null) { return; } if (WebPartManager == null || String.IsNullOrEmpty(_importedPartDescription)) { _availableWebPartDescriptions = new WebPartDescriptionCollection(); return; } // Run in minimal trust PermissionSet pset = new PermissionSet(PermissionState.None); // add in whatever perms are appropriate pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); pset.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal)); pset.PermitOnly(); bool permitOnly = true; string title = null; string description = null; string icon = null; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { // Get the WebPart description from its saved XML description. using (StringReader sr = new StringReader(_importedPartDescription)) { using (XmlReader reader = XmlUtils.CreateXmlReader(sr)) { if (reader != null) { reader.MoveToContent(); // Check if imported part is authorized // Get to the metadata reader.MoveToContent(); reader.ReadStartElement(WebPartManager.ExportRootElement); reader.ReadStartElement(WebPartManager.ExportPartElement); reader.ReadStartElement(WebPartManager.ExportMetaDataElement); // Get the type name string partTypeName = null; string userControlTypeName = null; while (reader.Name != WebPartManager.ExportTypeElement) { reader.Skip(); if (reader.EOF) { throw new EndOfStreamException(); } } if (reader.Name == WebPartManager.ExportTypeElement) { partTypeName = reader.GetAttribute(WebPartManager.ExportTypeNameAttribute); userControlTypeName = reader.GetAttribute(WebPartManager.ExportUserControlSrcAttribute); } // If we are in shared scope, we are importing a shared WebPart bool isShared = (WebPartManager.Personalization.Scope == PersonalizationScope.Shared); if (!String.IsNullOrEmpty(partTypeName)) { // Need medium trust to call BuildManager.GetType() PermissionSet mediumPset = new PermissionSet(PermissionState.None); mediumPset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); mediumPset.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium)); CodeAccessPermission.RevertPermitOnly(); permitOnly = false; mediumPset.PermitOnly(); permitOnly = true; Type partType = WebPartUtil.DeserializeType(partTypeName, true); CodeAccessPermission.RevertPermitOnly(); permitOnly = false; pset.PermitOnly(); permitOnly = true; // First check if the type is authorized if (!WebPartManager.IsAuthorized(partType, null, null, isShared)) { _importErrorMessage = SR.GetString(SR.WebPartManager_ForbiddenType); return; } // If the type is not a webpart, create a generic Web Part if (!partType.IsSubclassOf(typeof(WebPart)) && !partType.IsSubclassOf(typeof(Control))) { // We only allow for Controls (VSWhidbey 428511) _importErrorMessage = SR.GetString(SR.WebPartManager_TypeMustDeriveFromControl); return; } } else { // Check if the path is authorized if (!WebPartManager.IsAuthorized(typeof(UserControl), userControlTypeName, null, isShared)) { _importErrorMessage = SR.GetString(SR.WebPartManager_ForbiddenType); return; } } while (!reader.EOF) { while (!reader.EOF && !(reader.NodeType == XmlNodeType.Element && reader.Name == WebPartManager.ExportPropertyElement)) { reader.Read(); } if (reader.EOF) { break; } string name = reader.GetAttribute(WebPartManager.ExportPropertyNameAttribute); if (name == TitlePropertyName) { title = reader.ReadElementString(); } else if (name == DescriptionPropertyName) { description = reader.ReadElementString(); } else if (name == IconPropertyName) { string url = reader.ReadElementString().Trim(); if (!CrossSiteScriptingValidation.IsDangerousUrl(url)) { icon = url; } } else { reader.Read(); continue; } if (title != null && description != null && icon != null) { break; } reader.Read(); } } } if (String.IsNullOrEmpty(title)) { title = SR.GetString(SR.Part_Untitled); } _availableWebPartDescriptions = new WebPartDescriptionCollection( new WebPartDescription[] { new WebPartDescription(ImportedWebPartID, title, description, icon) }); } } catch (XmlException) { _importErrorMessage = SR.GetString(SR.WebPartManager_ImportInvalidFormat); return; } catch { _importErrorMessage = (!String.IsNullOrEmpty(_importErrorMessage)) ? _importErrorMessage : SR.GetString(SR.WebPart_DefaultImportErrorMessage); return; } finally { if (permitOnly) { // revert if you're not just exiting the stack frame anyway CodeAccessPermission.RevertPermitOnly(); } } } catch { throw; } }
/// <summary> /// Execute the IScriptRunner.Run method in the compiled_assembly /// </summary> /// <param name="compiled_assembly">compiled assembly</param> /// <param name="args">method arguments</param> /// <returns>object returned</returns> public static object Run(Assembly compiled_assembly, object[] args, PermissionSet permission_set) { if (compiled_assembly != null) { // put security restrict in place (PermissionState.None) permission_set.PermitOnly(); foreach (Type type in compiled_assembly.GetExportedTypes()) { foreach (Type interface_type in type.GetInterfaces()) { if (interface_type == typeof(IScriptRunner)) { ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes); if ((constructor != null) && (constructor.IsPublic)) { // construct object using default constructor IScriptRunner obj = constructor.Invoke(null) as IScriptRunner; if (obj != null) { return obj.Run(args); } else { throw new Exception("Invalid C# code!"); } } else { throw new Exception("No default constructor was found!"); } } else { throw new Exception("IScriptRunner is not implemented!"); } } } // lift security restrictions CodeAccessPermission.RevertPermitOnly(); } return null; }
internal string GetHtmlErrorMessage(bool dontShowSensitiveInfo) { this.PrepareFormatter(); StringBuilder sb = new StringBuilder(); sb.Append("<html"); if (IsTextRightToLeft) { sb.Append(" dir=\"rtl\""); } sb.Append(">\r\n"); sb.Append(" <head>\r\n"); sb.Append(" <title>" + this.ErrorTitle + "</title>\r\n"); sb.Append(" <style>\r\n"); sb.Append(" body {font-family:\"Verdana\";font-weight:normal;font-size: .7em;color:black;} \r\n"); sb.Append(" p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n"); sb.Append(" b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n"); sb.Append(" H1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n"); sb.Append(" H2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n"); sb.Append(" pre {font-family:\"Lucida Console\";font-size: .9em}\r\n"); sb.Append(" .marker {font-weight: bold; color: black;text-decoration: none;}\r\n"); sb.Append(" .version {color: gray;}\r\n"); sb.Append(" .error {margin-bottom: 10px;}\r\n"); sb.Append(" .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }\r\n"); sb.Append(" </style>\r\n"); sb.Append(" </head>\r\n\r\n"); sb.Append(" <body bgcolor=\"white\">\r\n\r\n"); sb.Append(" <span><H1>" + System.Web.SR.GetString("Error_Formatter_ASPNET_Error", new object[] { HttpRuntime.AppDomainAppVirtualPath }) + "<hr width=100% size=1 color=silver></H1>\r\n\r\n"); sb.Append(" <h2> <i>" + this.ErrorTitle + "</i> </h2></span>\r\n\r\n"); sb.Append(" <font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif \">\r\n\r\n"); sb.Append(" <b> " + System.Web.SR.GetString("Error_Formatter_Description") + " </b>" + this.Description + "\r\n"); sb.Append(" <br><br>\r\n\r\n"); if (this.MiscSectionTitle != null) { sb.Append(" <b> " + this.MiscSectionTitle + ": </b>" + this.MiscSectionContent + "<br><br>\r\n\r\n"); } this.WriteColoredSquare(sb, this.ColoredSquareTitle, this.ColoredSquareDescription, this.ColoredSquareContent, this.WrapColoredSquareContentLines); if (this.ShowSourceFileInfo) { string displayPath = this.GetDisplayPath(); if (displayPath == null) { displayPath = System.Web.SR.GetString("Error_Formatter_No_Source_File"); } sb.Append(string.Concat(new object[] { " <b> ", System.Web.SR.GetString("Error_Formatter_Source_File"), " </b> ", displayPath, "<b> ", System.Web.SR.GetString("Error_Formatter_Line"), " </b> ", this.SourceFileLineNumber, "\r\n" })); sb.Append(" <br><br>\r\n\r\n"); } ConfigurationErrorsException exception = this.Exception as ConfigurationErrorsException; if ((exception != null) && (exception.Errors.Count > 1)) { sb.Append(string.Format(CultureInfo.InvariantCulture, "<br><div class=\"expandable\" onclick=\"OnToggleTOCLevel1('{0}')\">{1}:</div>\r\n<div id=\"{0}\" style=\"display: none;\">\r\n <br><table width=100% bgcolor=\"#ffffcc\">\r\n <tr>\r\n <td>\r\n <code><pre>\r\n\r\n", new object[] { "additionalConfigurationErrors", System.Web.SR.GetString("TmplConfigurationAdditionalError") })); bool flag = false; try { PermissionSet namedPermissionSet = HttpRuntime.NamedPermissionSet; if (namedPermissionSet != null) { namedPermissionSet.PermitOnly(); flag = true; } int num = 0; foreach (ConfigurationException exception2 in exception.Errors) { if (num > 0) { sb.Append(exception2.Message); sb.Append("<BR/>\r\n"); } num++; } } finally { if (flag) { CodeAccessPermission.RevertPermitOnly(); } } sb.Append(" </pre></code>\r\n\r\n </td>\r\n </tr>\r\n </table>\r\n\r\n \r\n\r\n</div>\r\n"); sb.Append("\r\n <script type=\"text/javascript\">\r\n function OnToggleTOCLevel1(level2ID)\r\n {\r\n var elemLevel2 = document.getElementById(level2ID);\r\n if (elemLevel2.style.display == 'none')\r\n {\r\n elemLevel2.style.display = '';\r\n }\r\n else {\r\n elemLevel2.style.display = 'none';\r\n }\r\n }\r\n </script>\r\n "); } if ((!dontShowSensitiveInfo && (this.Exception != null)) && HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { this.WriteFusionLogWithAssert(sb); } this.WriteColoredSquare(sb, this.ColoredSquare2Title, this.ColoredSquare2Description, this.ColoredSquare2Content, false); if (!dontShowSensitiveInfo && !this._dontShowVersion) { sb.Append(" <hr width=100% size=1 color=silver>\r\n\r\n"); sb.Append(" <b>" + System.Web.SR.GetString("Error_Formatter_Version") + "</b> " + System.Web.SR.GetString("Error_Formatter_CLR_Build") + VersionInfo.ClrVersion + System.Web.SR.GetString("Error_Formatter_ASPNET_Build") + VersionInfo.EngineVersion + "\r\n\r\n"); sb.Append(" </font>\r\n\r\n"); } sb.Append(" </body>\r\n"); sb.Append("</html>\r\n"); sb.Append(this.PostMessage); return(sb.ToString()); }