public override object Execute(Object o, IList args) { IStackWalk permission = null; try { permission = CreateStackWalk(); if (this.PermitOnly) { permission.PermitOnly(); } else { permission.Deny(); } return(this.Invoker.Execute(o, args)); } finally { if (permission != null) { if (this.PermitOnly) { CodeAccessPermission.RevertPermitOnly(); } else { CodeAccessPermission.RevertDeny(); } } } }
internal void Deserialize(Stream o, string cryptoKey, CustomLicenseContext context) { IFormatter formatter = new BinaryFormatter(); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).PermitOnly(); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert(); object obj = default(object); try { obj = formatter.Deserialize(o); } finally { CodeAccessPermission.RevertAssert(); CodeAccessPermission.RevertPermitOnly(); } if (obj is object[]) { object[] array = (object[])obj; if (array[0] is string && (string)array[0] == cryptoKey) { context.savedLicenseKeys = (Hashtable)array[1]; } } }
public static void Main(string[] args) { //<Snippet2> Console.WriteLine("Creating a permission with the Flags property =" + " ProtectData."); DataProtectionPermission sp = new DataProtectionPermission( DataProtectionPermissionFlags.ProtectData); sp.PermitOnly(); //</Snippet2> // Protect the data ProtectData(); // This should fail without the correct permission UnprotectData(); // Revert the permission that limited access CodeAccessPermission.RevertPermitOnly(); // This should now work. UnprotectData(); // Demonstrate the behavior of the class members. ShowMembers(); Console.WriteLine("Press the Enter key to exit."); Console.ReadKey(); return; }
internal static void Deserialize(Stream o, string cryptoKey, RuntimeLicenseContext context) { IFormatter formatter = new BinaryFormatter(); object obj; new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).PermitOnly(); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert(); try { obj = formatter.Deserialize(o); } finally { CodeAccessPermission.RevertAssert(); CodeAccessPermission.RevertPermitOnly(); } if (obj is object[]) { object[] value = (object[])obj; if (value[0] is string && (string)value[0] == cryptoKey) { context.savedLicenseKeys = (Hashtable)value[1]; } } }
/* * Method: LoadAssembly * Purpose: Grabs an assembly off the disk and returns it as a * byte array. */ public byte [] LoadAssembly(string version, string assemblyFileName) { String assemblyRoot = ServerSettings.AssemblyPath; version = new Version(version).ToString(3); FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new string[] { assemblyRoot + "\\" + version }); byte[] bytes = null; try { permission.PermitOnly(); using (FileStream sourceStream = File.OpenRead(assemblyRoot + "\\" + version + "\\" + assemblyFileName)) { bytes = new byte[sourceStream.Length]; sourceStream.Read(bytes, 0, (int)sourceStream.Length); } } finally { CodeAccessPermission.RevertPermitOnly(); } return(bytes); }
/* * Method: RemoveAssembly * Purpose: Attempts to delete an assembly from the servers disk * cache. */ public void RemoveAssembly(string version, string assemblyFileName) { String assemblyRoot = ServerSettings.AssemblyPath; version = new Version(version).ToString(3); DirectoryInfo path = new DirectoryInfo(assemblyRoot + "\\" + version); if (!path.Exists) { return; } FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new string[] { assemblyRoot + "\\" + version }); try { permission.PermitOnly(); if (File.Exists(assemblyRoot + "\\" + version + "\\" + assemblyFileName)) { File.Delete(assemblyRoot + "\\" + version + "\\" + assemblyFileName); } } finally { CodeAccessPermission.RevertPermitOnly(); } }
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(); } } }
/// <summary> /// Saves the array of bytes given an assembly full name to /// the private assembly cache. /// </summary> /// <param name="bytes">The bytes of the assembly.</param> /// <param name="fullName">The full name of the original assembly.</param> public void SaveOrganismBytes(byte[] bytes, string fullName) { var directory = AssemblyDirectory; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var fileName = GetFileName(fullName); if (File.Exists(fileName)) { return; } // Ensure that the caller can't pass us a name that actually makes this file get created somewhere else var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { directory }); try { permission.PermitOnly(); var targetStream = File.Create(fileName); try { targetStream.Write(bytes, 0, bytes.Length); } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(fileName); throw; } finally { targetStream.Close(); } } finally { CodeAccessPermission.RevertPermitOnly(); } OnPacAssembliesChanged(new EventArgs()); }
/* * Method: SaveAssembly * Purpose: Attemps to save a byte array as an assembly on the * servers disk cache. */ public void SaveAssembly(byte [] assemblyCode, string version, string assemblyFileName) { String assemblyRoot = ServerSettings.AssemblyPath; version = new Version(version).ToString(3); DirectoryInfo path = new DirectoryInfo(assemblyRoot + "\\" + version); if (!path.Exists) { path.Create(); } FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new string[] { assemblyRoot + "\\" + version }); try { permission.PermitOnly(); // Use CreateNew to create so we get an exception if the file already exists -- it never should string pathToAssembly = assemblyRoot + "\\" + version + "\\" + assemblyFileName; if (File.Exists(pathToAssembly)) { throw new ApplicationException("an assembly with the same filename already exists in the server"); } using (FileStream targetStream = File.Open(pathToAssembly, FileMode.CreateNew)) { try { targetStream.Write(assemblyCode, 0, assemblyCode.Length); targetStream.Close(); } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(pathToAssembly); throw; } } } finally { CodeAccessPermission.RevertPermitOnly(); } }
public static void Main(string[] args) { try { // PermissionsHelper.InternetZone corresponds to the PermissionSet for partial trust. // PermissionsHelper.InternetZone.PermitOnly(); MemoryStream memoryStream = new MemoryStream(); new DataContractSerializer(typeof(DataNode)). WriteObject(memoryStream, new DataNode()); } finally { CodeAccessPermission.RevertPermitOnly(); } }
static void ParseLicense(Type type, object instance, Stream stream, out string userName, out string licenseKey, out string assemblyName, out CultureInfo culture) { object obj2; IFormatter formatter = new BinaryFormatter(); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).PermitOnly(); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert(); try { obj2 = formatter.Deserialize(stream); //var objArray = (object[])obj2; //userName = (string)objArray[0]; //licenseKey = (string)objArray[1]; var h = obj2 as System.Collections.Hashtable; if (h == null) { throw Error.LicenseFileErrorFormat(type, instance); } userName = h["UserName"] as string; if (userName == null) { throw Error.CannotGetUserName(type, instance); } //============================================================================== // 说明:key 允许为空,当为 Free 版本时 licenseKey = h["LicenseKey"] as string; if (licenseKey == null && !string.Equals(userName, Constants.FreeUserName, StringComparison.CurrentCultureIgnoreCase)) { throw Error.CannotGetLicenseKey(type, instance); } //============================================================================== assemblyName = h["AssemblyName"] as string; if (assemblyName == null) { throw Error.CannotGetAssemblyName(type, instance); } culture = h["Culture"] as CultureInfo; } finally { CodeAccessPermission.RevertAssert(); CodeAccessPermission.RevertPermitOnly(); } }
static void ExecuteInSandbox(PermissionSet permissionSet, Action action) { permissionSet.PermitOnly(); try { action(); } catch (Exception e) { Console.WriteLine(e.GetType().ToString() + ": " + e.Message); } finally { CodeAccessPermission.RevertPermitOnly(); } }
/// <summary> /// Determine if the assembly with the given full name exists /// within the PAC. /// </summary> /// <param name="fullName">The full name of the assembly to check for.</param> /// <returns>True if the assembly exists, false otherwise.</returns> public Boolean Exists(string fullName) { bool exists; var asmDir = Path.GetFullPath(AssemblyDirectory); // Make sure we can't be hacked to return whether files exist by only allowing our code // to access files in the assembly directory. var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { asmDir }); try { permission.PermitOnly(); exists = File.Exists(GetFileName(fullName)); } finally { CodeAccessPermission.RevertPermitOnly(); } return(exists); }
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> /// 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) { // security is not implemented yet! // using Utilties.PrivateStorage can save but not display in Notepad // plus the output is saved in C:\Users\<user>\AppData\Local\IsolatedStorage\... // no control over where to save make QuranCode unportable applicaton //// restrict code security //???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)); } throw new Exception("Invalid C# code!"); } throw new Exception("No default constructor was found!"); } throw new Exception("IScriptRunner is not implemented!"); } } // revert security restrictions CodeAccessPermission.RevertPermitOnly(); } return(null); }
/// <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); }
/// <summary> /// Blacklist a series of assemblies by setting their assemblies to zero length /// files. This is a way of ensuring that we don't load them again, or replace them /// with fresh working copies because the file name gets reserved with an invalid assembly. /// </summary> /// <param name="assemblies">The assemblies to be blacklisted.</param> public void BlacklistAssemblies(string[] assemblies) { // Ensure that the caller can't pass us a name that actually makes this file get created somewhere else var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { AssemblyDirectory }); try { permission.PermitOnly(); if (assemblies != null) { foreach (var assembly in assemblies) { var fileName = GetFileName(assembly); try { // Replace this file with a zero length file (or create one), so we won't get it again using (var stream = File.Create(fileName)) { stream.Close(); } } catch (Exception e) { Debug.WriteLine("Error blacklisting organism:"); ErrorLog.LogHandledException(e); } } } } finally { CodeAccessPermission.RevertPermitOnly(); } }
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(); } } }
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()); }
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; } }
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"); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { if (requestMsg != null) { // The message has already been deserialized so delegate to the next sink. return(_nextSink.ProcessMessage( sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream)); } if (requestHeaders == null) { throw new ArgumentNullException("requestHeaders"); } BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders; ServerProcessing processing; responseHeaders = null; responseStream = null; String verb = null; String contentType = null; bool bCanServiceRequest = true; // determine the content type String contentTypeHeader = null; if (wkRequestHeaders != null) { contentTypeHeader = wkRequestHeaders.ContentType; } else { contentTypeHeader = requestHeaders["Content-Type"] as String; } if (contentTypeHeader != null) { String charsetValue; HttpChannelHelper.ParseContentType(contentTypeHeader, out contentType, out charsetValue); } // check to see if Content-Type matches if ((contentType != null) && (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0)) { bCanServiceRequest = false; } // check for http specific verbs if (_protocol == Protocol.Http) { verb = (String)requestHeaders["__RequestVerb"]; if (!verb.Equals("POST") && !verb.Equals("M-POST")) { bCanServiceRequest = false; } } // either delegate or return an error message if we can't service the request if (!bCanServiceRequest) { // delegate to next sink if available if (_nextSink != null) { return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream)); } else { // send back an error message if (_protocol == Protocol.Http) { // return a client bad request error responseHeaders = new TransportHeaders(); responseHeaders["__HttpStatusCode"] = "400"; responseHeaders["__HttpReasonPhrase"] = "Bad Request"; responseStream = null; responseMsg = null; return(ServerProcessing.Complete); } else { // The transport sink will catch this and do something here. throw new RemotingException( CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat")); } } } try { String objectUri = null; bool bIsCustomErrorEnabled = true; object oIsCustomErrorEnabled = requestHeaders["__CustomErrorsEnabled"]; if (oIsCustomErrorEnabled != null && oIsCustomErrorEnabled is bool) { bIsCustomErrorEnabled = (bool)oIsCustomErrorEnabled; } CallContext.SetData("__CustomErrorsEnabled", bIsCustomErrorEnabled); if (wkRequestHeaders != null) { objectUri = wkRequestHeaders.RequestUri; } else { objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri]; } if (objectUri != lastUri && RemotingServices.GetServerTypeForUri(objectUri) == null) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished")); } else { lastUri = objectUri; } PermissionSet currentPermissionSet = null; if (this.TypeFilterLevel != TypeFilterLevel.Full) { currentPermissionSet = new PermissionSet(PermissionState.None); currentPermissionSet.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter)); } try { if (currentPermissionSet != null) { currentPermissionSet.PermitOnly(); } // Deserialize Request - Stream to IMessage requestMsg = CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding, this.TypeFilterLevel); } finally { if (currentPermissionSet != null) { CodeAccessPermission.RevertPermitOnly(); } } requestStream.Close(); if (requestMsg == null) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage")); } // Dispatch Call sinkStack.Push(this, null); processing = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); // make sure that responseStream is null if (responseStream != null) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream")); } switch (processing) { case ServerProcessing.Complete: { if (responseMsg == null) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage")); } sinkStack.Pop(this); SerializeResponse(sinkStack, responseMsg, ref responseHeaders, out responseStream); break; } // case ServerProcessing.Complete case ServerProcessing.OneWay: { sinkStack.Pop(this); break; } // case ServerProcessing.OneWay: case ServerProcessing.Async: { sinkStack.Store(this, null); break; } // case ServerProcessing.Async } // switch (processing) } catch (Exception e) { processing = ServerProcessing.Complete; responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg)); // CallContext.SetData("__ClientIsClr", true); responseStream = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning); CallContext.FreeNamedDataSlot("__ClientIsClr"); responseStream.Position = 0; responseHeaders = new TransportHeaders(); if (_protocol == Protocol.Http) { responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType; } } finally{ CallContext.FreeNamedDataSlot("__CustomErrorsEnabled"); } return(processing); } // ProcessMessage
/// <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()); } } } }
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); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { ServerProcessing complete; if (requestMsg != null) { return(this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream)); } if (requestHeaders == null) { throw new ArgumentNullException("requestHeaders"); } BaseTransportHeaders headers = requestHeaders as BaseTransportHeaders; responseHeaders = null; responseStream = null; string str = null; string str2 = null; bool flag = true; string contentType = null; if (headers != null) { contentType = headers.ContentType; } else { contentType = requestHeaders["Content-Type"] as string; } if (contentType != null) { string str4; HttpChannelHelper.ParseContentType(contentType, out str2, out str4); } if ((str2 != null) && (string.Compare(str2, "text/xml", StringComparison.Ordinal) != 0)) { flag = false; } if (this._protocol == Protocol.Http) { str = (string)requestHeaders["__RequestVerb"]; if (!str.Equals("POST") && !str.Equals("M-POST")) { flag = false; } } if (!flag) { if (this._nextSink != null) { return(this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream)); } if (this._protocol != Protocol.Http) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat")); } responseHeaders = new TransportHeaders(); responseHeaders["__HttpStatusCode"] = "400"; responseHeaders["__HttpReasonPhrase"] = "Bad Request"; responseStream = null; responseMsg = null; return(ServerProcessing.Complete); } bool bClientIsClr = true; try { string str7; string uRI = null; if (headers != null) { uRI = headers.RequestUri; } else { uRI = (string)requestHeaders["__RequestUri"]; } if (RemotingServices.GetServerTypeForUri(uRI) == null) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished")); } if (this._protocol == Protocol.Http) { string str6 = (string)requestHeaders["User-Agent"]; if (str6 != null) { if (str6.IndexOf("MS .NET Remoting") == -1) { bClientIsClr = false; } } else { bClientIsClr = false; } } bool data = true; object obj2 = requestHeaders["__CustomErrorsEnabled"]; if ((obj2 != null) && (obj2 is bool)) { data = (bool)obj2; } CallContext.SetData("__CustomErrorsEnabled", data); Header[] channelHeaders = this.GetChannelHeaders(requestHeaders, out str7); PermissionSet set = null; if (this.TypeFilterLevel != System.Runtime.Serialization.Formatters.TypeFilterLevel.Full) { set = new PermissionSet(PermissionState.None); set.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter)); } try { if (set != null) { set.PermitOnly(); } requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, channelHeaders, this._strictBinding, this.TypeFilterLevel); } finally { if (set != null) { CodeAccessPermission.RevertPermitOnly(); } } requestStream.Close(); if (requestMsg == null) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage")); } if ((str7 != null) && !SoapServices.IsSoapActionValidForMethodBase(str7, ((IMethodMessage)requestMsg).MethodBase)) { throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"), new object[] { str7 })); } sinkStack.Push(this, null); complete = this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); if (responseStream != null) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream")); } switch (complete) { case ServerProcessing.Complete: if (responseMsg == null) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage")); } break; case ServerProcessing.OneWay: sinkStack.Pop(this); return(complete); case ServerProcessing.Async: sinkStack.Store(this, null); return(complete); default: return(complete); } sinkStack.Pop(this); this.SerializeResponse(sinkStack, responseMsg, bClientIsClr, ref responseHeaders, out responseStream); return(complete); } catch (Exception exception) { complete = ServerProcessing.Complete; responseMsg = new ReturnMessage(exception, (requestMsg == null) ? ((IMethodCallMessage) new System.Runtime.Remoting.Channels.Http.ErrorMessage()) : ((IMethodCallMessage)requestMsg)); CallContext.SetData("__ClientIsClr", bClientIsClr); responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, this._includeVersioning); CallContext.FreeNamedDataSlot("__ClientIsClr"); responseStream.Position = 0L; responseHeaders = new TransportHeaders(); if (this._protocol == Protocol.Http) { responseHeaders["__HttpStatusCode"] = "500"; responseHeaders["__HttpReasonPhrase"] = "Internal Server Error"; responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\""; } } finally { CallContext.FreeNamedDataSlot("__CustomErrorsEnabled"); } return(complete); }
/// <summary> /// Save an assembly along with symbols given a full path to the /// assembly and symbols to the cache. /// </summary> /// <param name="assemblyPath">A local path to the assembly.</param> /// <param name="symbolPath">A local path to the symbols.</param> /// <param name="fullName">The full name of the assembly.</param> public void SaveOrganismAssembly(string assemblyPath, string symbolPath, string fullName) { var directory = AssemblyDirectory; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var fileName = GetFileName(fullName); var symName = Path.ChangeExtension(GetFileName(fullName), ".pdb"); if (File.Exists(fileName)) { return; } var reportPath = Path.Combine(GameConfig.ApplicationDirectory, Guid.NewGuid() + ".xml"); var validAssembly = checkAssemblyWithReporting(assemblyPath, reportPath); if (validAssembly == 0) { throw OrganismAssemblyFailedValidationException.GenerateExceptionFromXml(reportPath); } if (File.Exists(reportPath)) { File.Delete(reportPath); } var sourceStream = File.OpenRead(assemblyPath); FileStream symStream = null; try { if (!string.IsNullOrEmpty(symbolPath) && File.Exists(symbolPath)) { symStream = File.OpenRead(symbolPath); } } catch { // In case anything goes wrong with the symbols (access denied and others), we are good } // Ensure that the caller can't pass us a name that actually makes this file get created somewhere else var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { directory }); try { permission.PermitOnly(); var targetStream = File.Create(fileName); try { var bytes = new byte[65536]; int bytesRead; while ((bytesRead = sourceStream.Read(bytes, 0, 65536)) > 0) { targetStream.Write(bytes, 0, bytesRead); } } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(fileName); throw; } finally { targetStream.Close(); } if (symStream != null) { try { targetStream = File.Create(symName); try { var bytes = new byte[65536]; int bytesRead; while ((bytesRead = symStream.Read(bytes, 0, 65536)) > 0) { targetStream.Write(bytes, 0, bytesRead); } } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(symName); throw; } finally { targetStream.Close(); } } catch { // No reason to crash } } } finally { CodeAccessPermission.RevertPermitOnly(); sourceStream.Close(); } OnPacAssembliesChanged(new EventArgs()); }