static XmlILModule() { AssemblyName asmName; AssemblyBuilder asmBldr; CreateModulePermissionSet = new PermissionSet(PermissionState.None); // CreateDelegate demands MemberAccess permission CreateModulePermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); // DynamicMethod constructor demands ControlEvidence permissions. // Emitting symbols in DefineDynamicModule (to allow to debug the stylesheet) requires UnmanagedCode permission. CreateModulePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.UnmanagedCode)); AssemblyId = 0; // 1. LRE assembly only needs to execute // 2. No temp files need be created // 3. Never allow assembly to Assert permissions asmName = CreateAssemblyName(); asmBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); try { CreateModulePermissionSet.Assert(); // Add custom attribute to assembly marking it as security transparent so that Assert will not be allowed // and link demands will be converted to full demands. asmBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.Transparent, new object[] {})); // Store LREModule once. If multiple threads are doing this, then some threads might get different // modules. This is OK, since it's not mandatory to share, just preferable. LREModule = asmBldr.DefineDynamicModule("System.Xml.Xsl.CompiledQuery", false); } finally { CodeAccessPermission.RevertAssert(); } }
public void Open() { if(State != CommunicationState.Created) { return; } try { Opening(this,EventArgs.Empty); //Permission required to read the providers application name and access config PermissionSet permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal)); permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); permissions.Assert(); m_ServiceHostActivator.MembershipApplicationName = Membership.ApplicationName; if(Roles.Enabled) { m_ServiceHostActivator.RolesApplicationName = Roles.ApplicationName; } PermissionSet.RevertAssert(); m_ServiceHostActivator.Open(); State = CommunicationState.Opened; Opened(this,EventArgs.Empty); } catch { State = CommunicationState.Faulted; } }
private static string GetApplicationInstanceId(this Assembly entry) { var set = new PermissionSet(PermissionState.None); set.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); set.Assert(); var typeLibGuidForAssembly = Marshal.GetTypeLibGuidForAssembly(entry); var strArray = entry.GetName().Version.ToString().Split(".".ToCharArray()); PermissionSet.RevertAssert(); return typeLibGuidForAssembly + strArray[0] + "." + strArray[1]; }
public static void Socket() { var set = new PermissionSet(PermissionState.None); set.AddPermission(new DnsPermission(PermissionState.Unrestricted)); set.AddPermission(new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "173.194.32.38", 80)); set.Assert(); var client = new TcpClient(); client.Connect("173.194.32.38", 80); Console.WriteLine("Connected to google: {0}", client.Connected); client.Close(); CodeAccessPermission.RevertAssert(); }
private void SetBackgroundImage() { // needed for OleInitialize Application.OleRequired(); NativeMethods.LVBKIMAGE lvbkImage = new NativeMethods.LVBKIMAGE(); lvbkImage.xOffset = 0; lvbkImage.yOffset = 0; // first, is there an existing temporary file to delete, remember its name // so that we can delete it if the list control doesn't... string fileNameToDelete = this.backgroundImageFileName; if (this.BackgroundImage != null) { // the list view needs these permissions when the app runs on an UNC share // and the list view creates / destroys temporary files for its background image // SECREVIEW : Safe to assert FileIO & Environment permissions here, just creating/deleting temp files. // EnvironmentPermission envPermission = new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP"); FileIOPermission fiop = new FileIOPermission(PermissionState.Unrestricted); System.Security.PermissionSet permSet = new System.Security.PermissionSet(PermissionState.Unrestricted); permSet.AddPermission(envPermission); permSet.AddPermission(fiop); permSet.Assert(); // save the image to a temporary file name try { string tempDirName = System.IO.Path.GetTempPath(); System.Text.StringBuilder sb = new System.Text.StringBuilder(1024); UnsafeNativeMethods.GetTempFileName(tempDirName, this.GenerateRandomName(), 0, sb); this.backgroundImageFileName = sb.ToString(); this.BackgroundImage.Save(this.backgroundImageFileName, System.Drawing.Imaging.ImageFormat.Bmp); } finally { System.Security.PermissionSet.RevertAssert(); } lvbkImage.pszImage = this.backgroundImageFileName; lvbkImage.cchImageMax = this.backgroundImageFileName.Length + 1; lvbkImage.ulFlags = NativeMethods.LVBKIF_SOURCE_URL; if (BackgroundImageTiled) lvbkImage.ulFlags |= NativeMethods.LVBKIF_STYLE_TILE; else lvbkImage.ulFlags |= NativeMethods.LVBKIF_STYLE_NORMAL; } else { lvbkImage.ulFlags = NativeMethods.LVBKIF_SOURCE_NONE; this.backgroundImageFileName = String.Empty; } UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), NativeMethods.LVM_SETBKIMAGE, 0, lvbkImage); if (String.IsNullOrEmpty(fileNameToDelete)) { return; } // we need to cause a paint message on the win32 list view. This way the win 32 list view gives up // its reference to the previous image file it was hanging on to. // vsWhidbey 243708 // 8 strings should be good enough for us if (this.bkImgFileNames == null) { this.bkImgFileNames = new string[BKIMGARRAYSIZE]; this.bkImgFileNamesCount = -1; } if (this.bkImgFileNamesCount == BKIMGARRAYSIZE - 1) { // it should be fine to delete the file name that was added first. // if it's not fine, then increase BKIMGARRAYSIZE this.DeleteFileName(this.bkImgFileNames[0]); this.bkImgFileNames[0] = this.bkImgFileNames[1]; this.bkImgFileNames[1] = this.bkImgFileNames[2]; this.bkImgFileNames[2] = this.bkImgFileNames[3]; this.bkImgFileNames[3] = this.bkImgFileNames[4]; this.bkImgFileNames[4] = this.bkImgFileNames[5]; this.bkImgFileNames[5] = this.bkImgFileNames[6]; this.bkImgFileNames[6] = this.bkImgFileNames[7]; this.bkImgFileNames[7] = null; this.bkImgFileNamesCount --; } this.bkImgFileNamesCount ++; this.bkImgFileNames[this.bkImgFileNamesCount] = fileNameToDelete; // now force the paint this.Refresh(); }
private string GetSystemSound(string soundName) { string soundFile = null; string regPath = string.Format(CultureInfo.InvariantCulture, SYSTEM_SOUNDS_REGISTRY_LOCATION, soundName); PermissionSet permissions = new PermissionSet(null); permissions.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, SYSTEM_SOUNDS_REGISTRY_BASE)); permissions.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); permissions.Assert(); try { using (RegistryKey soundKey = Registry.CurrentUser.OpenSubKey(regPath)) { if (soundKey != null) { soundFile = (string)(soundKey.GetValue("")); } } } // When the value of the register key is empty, the IndexOutofRangeException is thrown. // Please see Dev10 bug 586158 for more details. catch (System.IndexOutOfRangeException) { } finally { CodeAccessPermission.RevertAssert(); } return soundFile; }
internal static string GetTempAssemblyPath(string baseDir, Assembly assembly, string defaultNamespace) { if (assembly.IsDynamic) { throw new InvalidOperationException(Res.GetString(Res.XmlPregenAssemblyDynamic)); } PermissionSet perms = new PermissionSet(PermissionState.None); perms.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.Assert(); try { if (baseDir != null && baseDir.Length > 0) { // check that the dirsctory exists if (!Directory.Exists(baseDir)) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingDirectory, baseDir)); } } else { baseDir = Path.GetTempPath(); // check that the dirsctory exists if (!Directory.Exists(baseDir)) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingTempDirectory)); } } #if MONO baseDir = Path.Combine (baseDir, GetTempAssemblyName(assembly.GetName(), defaultNamespace)); #else if (baseDir.EndsWith("\\", StringComparison.Ordinal)) baseDir += GetTempAssemblyName(assembly.GetName(), defaultNamespace); else baseDir += "\\" + GetTempAssemblyName(assembly.GetName(), defaultNamespace); #endif } finally { CodeAccessPermission.RevertAssert(); } return baseDir + ".dll"; }
public void Generate() { if (this._resourceList == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved")); } BinaryWriter writer = new BinaryWriter(this._output, Encoding.UTF8); List<string> types = new List<string>(); writer.Write(ResourceManager.MagicNumber); writer.Write(ResourceManager.HeaderVersionNumber); MemoryStream output = new MemoryStream(240); BinaryWriter writer2 = new BinaryWriter(output); writer2.Write(MultitargetingHelpers.GetAssemblyQualifiedName(typeof(ResourceReader), this.typeConverter)); writer2.Write(ResourceManager.ResSetTypeName); writer2.Flush(); writer.Write((int) output.Length); writer.Write(output.GetBuffer(), 0, (int) output.Length); writer.Write(2); int count = this._resourceList.Count; if (this._preserializedData != null) { count += this._preserializedData.Count; } writer.Write(count); int[] keys = new int[count]; int[] items = new int[count]; int index = 0; MemoryStream stream2 = new MemoryStream(count * 40); BinaryWriter writer3 = new BinaryWriter(stream2, Encoding.Unicode); Stream stream3 = null; string path = null; PermissionSet set = new PermissionSet(PermissionState.None); set.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); set.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); try { set.Assert(); path = Path.GetTempFileName(); File.SetAttributes(path, FileAttributes.NotContentIndexed | FileAttributes.Temporary); stream3 = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 0x1000, FileOptions.SequentialScan | FileOptions.DeleteOnClose); } catch (UnauthorizedAccessException) { stream3 = new MemoryStream(); } catch (IOException) { stream3 = new MemoryStream(); } finally { PermissionSet.RevertAssert(); } using (stream3) { BinaryWriter store = new BinaryWriter(stream3, Encoding.UTF8); IFormatter objFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Persistence | StreamingContextStates.File)); SortedList list2 = new SortedList(this._resourceList, FastResourceComparer.Default); if (this._preserializedData != null) { foreach (KeyValuePair<string, PrecannedResource> pair in this._preserializedData) { list2.Add(pair.Key, pair.Value); } } IDictionaryEnumerator enumerator = list2.GetEnumerator(); while (enumerator.MoveNext()) { keys[index] = FastResourceComparer.HashFunction((string) enumerator.Key); items[index++] = (int) writer3.Seek(0, SeekOrigin.Current); writer3.Write((string) enumerator.Key); writer3.Write((int) store.Seek(0, SeekOrigin.Current)); object obj2 = enumerator.Value; ResourceTypeCode typeCode = this.FindTypeCode(obj2, types); Write7BitEncodedInt(store, (int) typeCode); PrecannedResource resource = obj2 as PrecannedResource; if (resource != null) { store.Write(resource.Data); } else { this.WriteValue(typeCode, obj2, store, objFormatter); } } writer.Write(types.Count); for (int i = 0; i < types.Count; i++) { writer.Write(types[i]); } Array.Sort<int, int>(keys, items); writer.Flush(); int num4 = ((int) writer.BaseStream.Position) & 7; if (num4 > 0) { for (int j = 0; j < (8 - num4); j++) { writer.Write("PAD"[j % 3]); } } foreach (int num6 in keys) { writer.Write(num6); } foreach (int num7 in items) { writer.Write(num7); } writer.Flush(); writer3.Flush(); store.Flush(); int num8 = (int) (writer.Seek(0, SeekOrigin.Current) + stream2.Length); num8 += 4; writer.Write(num8); writer.Write(stream2.GetBuffer(), 0, (int) stream2.Length); writer3.Close(); stream3.Position = 0L; stream3.CopyTo(writer.BaseStream); store.Close(); } writer.Flush(); this._resourceList = null; }
static Stream OpenRead(Uri resourceUri) { Stream result = null; #if !DISABLE_CAS_USE PermissionSet perms = new PermissionSet(PermissionState.Unrestricted); perms.Assert(); #endif try { WebClient webClient = new WebClient(); webClient.Credentials = CredentialCache.DefaultCredentials; result = webClient.OpenRead(resourceUri.ToString()); } catch (Exception e) { Debug.Fail(e.ToString()); } #if !DISABLE_CAS_USE finally { CodeAccessPermission.RevertAssert(); } #endif return result; }
internal bool FindCustomCategory(string category, out PerformanceCounterCategoryType categoryType) { RegistryKey key = null; RegistryKey baseKey = null; categoryType = PerformanceCounterCategoryType.Unknown; if (this.customCategoryTable == null) { Interlocked.CompareExchange(ref this.customCategoryTable, new Hashtable(StringComparer.OrdinalIgnoreCase), null); } if (this.customCategoryTable.ContainsKey(category)) { categoryType= (PerformanceCounterCategoryType) this.customCategoryTable[category]; return true; } else { //SECREVIEW: Whoever is able to call this function, must already // have demanded PerformanceCounterPermission // we can therefore assert the RegistryPermission. PermissionSet ps = new PermissionSet(PermissionState.None); ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted)); ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); ps.Assert(); try { string keyPath = ServicePath + "\\" + category + "\\Performance"; if (machineName == "." || String.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0) { key = Registry.LocalMachine.OpenSubKey(keyPath); } else { baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + this.machineName); if (baseKey != null) { try { key = baseKey.OpenSubKey(keyPath); } catch (SecurityException) { // we may not have permission to read the registry key on the remote machine. The security exception // is thrown when RegOpenKeyEx returns ERROR_ACCESS_DENIED or ERROR_BAD_IMPERSONATION_LEVEL // // In this case we return an 'Unknown' category type and 'false' to indicate the category is *not* custom. // categoryType = PerformanceCounterCategoryType.Unknown; this.customCategoryTable[category] = categoryType; return false; } } } if (key != null) { object systemDllName = key.GetValue("Library", null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (systemDllName != null && systemDllName is string && (String.Compare((string)systemDllName, PerformanceCounterLib.PerfShimName, StringComparison.OrdinalIgnoreCase) == 0 || ((string)systemDllName).EndsWith(PerformanceCounterLib.PerfShimFullNameSuffix, StringComparison.OrdinalIgnoreCase))) { object isMultiInstanceObject = key.GetValue("IsMultiInstance"); if (isMultiInstanceObject != null) { categoryType = (PerformanceCounterCategoryType) isMultiInstanceObject; if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance) categoryType = PerformanceCounterCategoryType.Unknown; } else categoryType = PerformanceCounterCategoryType.Unknown; object objectID = key.GetValue("First Counter"); if (objectID != null) { int firstID = (int)objectID; this.customCategoryTable[category] = categoryType; return true; } } } } finally { if (key != null) key.Close(); if (baseKey != null) baseKey.Close(); PermissionSet.RevertAssert(); } } return false; }
private static bool TIPsWantToRun() { object obj; RegistryKey key; bool tipsWantToRun = false; PermissionSet ps = new PermissionSet(PermissionState.None); ps.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\CTF")); ps.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CURRENT_USER\\Software\\Microsoft\\CTF")); ps.Assert(); // BlessedAssert: try { key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\CTF", false); // Is cicero disabled completely for the current user? if (key != null) { obj = key.GetValue("Disable Thread Input Manager"); if (obj is int && (int)obj != 0) return false; } // Loop through all the TIP entries for machine and current user. tipsWantToRun = IterateSubKeys(Registry.LocalMachine, "SOFTWARE\\Microsoft\\CTF\\TIP",new IterateHandler(SingleTIPWantsToRun), true) == EnableState.Enabled; } finally { CodeAccessPermission.RevertAssert(); } return tipsWantToRun; }
private static bool LoadRecognizerDll() { // ISSUE-2005/01/14-WAYNEZEN, // We may hit the problem when an application already load mshwgst.dll from somewhere rather than the // directory we are looking for. The options to resolve this - // 1. We fail the recognition functionality. // 2. We unload the previous mshwgst.dll // 3. We switch the DllImport usage to the new dynamic PInvoke mechanism in Whidbey. Please refer to the blog // http://blogs.msdn.com/junfeng/archive/2004/07/14/181932.aspx. Then we don't have to unload the existing // mshwgst.dll. String path = null; System.Security.PermissionSet permissionSet = new PermissionSet(null); permissionSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, System.Security.AccessControl.AccessControlActions.View, GestureRecognizerFullPath)); permissionSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); permissionSet.Assert(); // BlessedAssert: try { RegistryKey regkey = Registry.LocalMachine; RegistryKey recognizerKey = regkey.OpenSubKey(GestureRecognizerPath); if (recognizerKey != null) { try { // Try to read the recognizer path subkey path = recognizerKey.GetValue(GestureRecognizerValueName) as string; if (path == null) { return false; } } finally { recognizerKey.Close(); } } else { // we couldn't find the path in the registry // no key to close return false; } } finally { CodeAccessPermission.RevertAssert(); } if (path != null) { IntPtr hModule = MS.Win32.UnsafeNativeMethods.LoadLibrary(path); // Check whether GetAlternateList exists in the loaded Dll. s_GetAlternateListExists = false; if ( hModule != IntPtr.Zero ) { s_GetAlternateListExists = MS.Win32.UnsafeNativeMethods.GetProcAddressNoThrow( new HandleRef(null, hModule), "GetAlternateList") != IntPtr.Zero ? true : false; } return hModule != IntPtr.Zero ? true : false; } return false; //path was null }
internal IContract GetContract() { if (_contract != null) return _contract; // in direct connect, the contract has not been created. Create it now. Object hav = _havReference.Target; if (hav == null) throw new InvalidOperationException(Res.AddInNoLongerAvailable); // Assert permission to the contracts, AddInSideAdapters, AddInViews and specific Addin directories only. PermissionSet permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.Combine(_token.PipelineRootDirectory, AddInStore.ContractsDirName))); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.Combine(_token.PipelineRootDirectory, AddInStore.AddInAdaptersDirName))); permissionSet.Assert(); Assembly.LoadFrom(_token._contract.Location); Assembly addinAdapterAssembly = Assembly.LoadFrom(_token._addinAdapter.Location); CodeAccessPermission.RevertAssert(); // Create the AddIn adapter for the addin ActivationWorker worker = new ActivationWorker(_token); _contract = worker.CreateAddInAdapter(hav, addinAdapterAssembly); return _contract; }
private void SetBackgroundImage() { Application.OleRequired(); System.Windows.Forms.NativeMethods.LVBKIMAGE lParam = new System.Windows.Forms.NativeMethods.LVBKIMAGE { xOffset = 0, yOffset = 0 }; string backgroundImageFileName = this.backgroundImageFileName; if (this.BackgroundImage != null) { EnvironmentPermission perm = new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP"); FileIOPermission permission2 = new FileIOPermission(PermissionState.Unrestricted); PermissionSet set = new PermissionSet(PermissionState.Unrestricted); set.AddPermission(perm); set.AddPermission(permission2); set.Assert(); try { string tempPath = Path.GetTempPath(); StringBuilder sb = new StringBuilder(0x400); System.Windows.Forms.UnsafeNativeMethods.GetTempFileName(tempPath, this.GenerateRandomName(), 0, sb); this.backgroundImageFileName = sb.ToString(); this.BackgroundImage.Save(this.backgroundImageFileName, ImageFormat.Bmp); } finally { PermissionSet.RevertAssert(); } lParam.pszImage = this.backgroundImageFileName; lParam.cchImageMax = this.backgroundImageFileName.Length + 1; lParam.ulFlags = 2; if (this.BackgroundImageTiled) { lParam.ulFlags |= 0x10; } else { lParam.ulFlags = lParam.ulFlags; } } else { lParam.ulFlags = 0; this.backgroundImageFileName = string.Empty; } System.Windows.Forms.UnsafeNativeMethods.SendMessage(new HandleRef(this, base.Handle), System.Windows.Forms.NativeMethods.LVM_SETBKIMAGE, 0, lParam); if (!string.IsNullOrEmpty(backgroundImageFileName)) { if (this.bkImgFileNames == null) { this.bkImgFileNames = new string[8]; this.bkImgFileNamesCount = -1; } if (this.bkImgFileNamesCount == 7) { this.DeleteFileName(this.bkImgFileNames[0]); this.bkImgFileNames[0] = this.bkImgFileNames[1]; this.bkImgFileNames[1] = this.bkImgFileNames[2]; this.bkImgFileNames[2] = this.bkImgFileNames[3]; this.bkImgFileNames[3] = this.bkImgFileNames[4]; this.bkImgFileNames[4] = this.bkImgFileNames[5]; this.bkImgFileNames[5] = this.bkImgFileNames[6]; this.bkImgFileNames[6] = this.bkImgFileNames[7]; this.bkImgFileNames[7] = null; this.bkImgFileNamesCount--; } this.bkImgFileNamesCount++; this.bkImgFileNames[this.bkImgFileNamesCount] = backgroundImageFileName; this.Refresh(); } }
private Hashtable GetStringTable(bool isHelp) { Hashtable hashtable; RegistryKey performanceData; PermissionSet set = new PermissionSet(PermissionState.None); set.AddPermission(new RegistryPermission(PermissionState.Unrestricted)); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); set.Assert(); if (string.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0) { performanceData = Registry.PerformanceData; } else { performanceData = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, this.machineName); } try { string[] strArray = null; int num = 14; int millisecondsTimeout = 0; while (num > 0) { try { if (!isHelp) { strArray = (string[]) performanceData.GetValue("Counter " + this.perfLcid); } else { strArray = (string[]) performanceData.GetValue("Explain " + this.perfLcid); } if ((strArray != null) && (strArray.Length != 0)) { break; } num--; if (millisecondsTimeout == 0) { millisecondsTimeout = 10; } else { Thread.Sleep(millisecondsTimeout); millisecondsTimeout *= 2; } continue; } catch (IOException) { strArray = null; break; } catch (InvalidCastException) { strArray = null; break; } } if (strArray == null) { return new Hashtable(); } hashtable = new Hashtable(strArray.Length / 2); for (int i = 0; i < (strArray.Length / 2); i++) { int num4; string str = strArray[(i * 2) + 1]; if (str == null) { str = string.Empty; } if (!int.TryParse(strArray[i * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out num4)) { if (isHelp) { throw new InvalidOperationException(SR.GetString("CategoryHelpCorrupt", new object[] { strArray[i * 2] })); } throw new InvalidOperationException(SR.GetString("CounterNameCorrupt", new object[] { strArray[i * 2] })); } hashtable[num4] = str; } } finally { performanceData.Close(); } return hashtable; }
internal bool FindCustomCategory(string category, out PerformanceCounterCategoryType categoryType) { RegistryKey key = null; RegistryKey key2 = null; categoryType = PerformanceCounterCategoryType.Unknown; if (this.customCategoryTable == null) { Interlocked.CompareExchange<Hashtable>(ref this.customCategoryTable, new Hashtable(StringComparer.OrdinalIgnoreCase), null); } if (this.customCategoryTable.ContainsKey(category)) { categoryType = (PerformanceCounterCategoryType) this.customCategoryTable[category]; return true; } PermissionSet set = new PermissionSet(PermissionState.None); set.AddPermission(new RegistryPermission(PermissionState.Unrestricted)); set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); set.Assert(); try { string name = @"SYSTEM\CurrentControlSet\Services\" + category + @"\Performance"; if ((this.machineName == ".") || (string.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0)) { key = Registry.LocalMachine.OpenSubKey(name); } else { key2 = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, @"\\" + this.machineName); if (key2 != null) { try { key = key2.OpenSubKey(name); } catch (SecurityException) { categoryType = PerformanceCounterCategoryType.Unknown; this.customCategoryTable[category] = (PerformanceCounterCategoryType) categoryType; return false; } } } if (key != null) { object obj2 = key.GetValue("Library"); if (((obj2 != null) && (obj2 is string)) && (string.Compare((string) obj2, "netfxperf.dll", StringComparison.OrdinalIgnoreCase) == 0)) { object obj3 = key.GetValue("IsMultiInstance"); if (obj3 != null) { categoryType = (PerformanceCounterCategoryType) obj3; if ((categoryType < PerformanceCounterCategoryType.Unknown) || (categoryType > PerformanceCounterCategoryType.MultiInstance)) { categoryType = PerformanceCounterCategoryType.Unknown; } } else { categoryType = PerformanceCounterCategoryType.Unknown; } object obj4 = key.GetValue("First Counter"); if (obj4 != null) { int num1 = (int) obj4; this.customCategoryTable[category] = (PerformanceCounterCategoryType) categoryType; return true; } } } } finally { if (key != null) { key.Close(); } if (key2 != null) { key2.Close(); } PermissionSet.RevertAssert(); } return false; }
private static IntPtr CriticalHandleWMGetobject(IntPtr wparam, IntPtr lparam, Visual root, IntPtr handle) { try { if (root == null) { // Valid case, but need to handle separately. For now, return 0 to avoid exceptions // in referencing this later on. Real solution is more complex, see WindowsClient#873800. return IntPtr.Zero; } AutomationPeer peer = null; if (root.CheckFlagsAnd(VisualFlags.IsUIElement)) { UIElement uiroot = (UIElement)root; peer = UIElementAutomationPeer.CreatePeerForElement(uiroot); //there si no specific peer for this UIElement, create a generic root if(peer == null) peer = uiroot.CreateGenericRootAutomationPeer(); if(peer != null) peer.Hwnd = handle; } // This can happen if the root visual is not UIElement. In this case, // attempt to find one in the visual tree. if (peer == null) { peer = UIElementAutomationPeer.GetRootAutomationPeer(root, handle); } if (peer == null) { return IntPtr.Zero; } // get the element proxy // it's ok to pass the same peer as reference connected peer here because // it's guaranteed to be a connected one (it's initialized as root already) IRawElementProviderSimple el = ElementProxy.StaticWrap(peer, peer); peer.AddToAutomationEventList(); // The assert here is considered OK // as we're assuming the WM_GETOBJECT is coming only from a PostMessage of an Hwnd. // to do the post message - you needed to have Unmanaged code permission // PermissionSet unpackPermissionSet = new PermissionSet(PermissionState.None); // below permissions needed to unpack an object. unpackPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter | SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.RemotingConfiguration)); unpackPermissionSet.AddPermission(new System.Net.DnsPermission(PermissionState.Unrestricted)); unpackPermissionSet.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted)); unpackPermissionSet.Assert(); try { return AutomationInteropProvider.ReturnRawElementProvider(handle, wparam, lparam, el); } finally { CodeAccessPermission.RevertAll(); } } #pragma warning disable 56500 catch (Exception e) { if(CriticalExceptions.IsCriticalException(e)) { throw; } return new IntPtr(Marshal.GetHRForException(e)); } #pragma warning restore 56500 }
internal Assembly ResolveAssembly(Object sender, ResolveEventArgs args) { System.Diagnostics.Contracts.Contract.Assert(_pipeline != null); String assemblyRef = args.Name; //Console.WriteLine("ResolveAssembly (in add-in's AD) called for {0}", assemblyRef); // Two purposes here: // 1) Ensure that our already-loaded pipeline components get upgraded // from the LoadFrom context to the default loader context. // 2) Any dependencies of our already-loaded pipeline components would // have been loaded in the LoadFrom context, and need to also be // manually upgraded to the default loader context. // We can do both of the above by calling LoadFrom on the appropriate // assemblies on disk, or by walking the list of already-loaded // assemblies, looking for the ones we need to upgrade. // Since we'll have multiple add-ins in the same AD, it may make the // most sense to simply look for an already-loaded assembly instead of // looking in directories on disk, to avoid conflicts. // Check to see if this assembly was already loaded in the // LoadFrom context. If so, upgrade it. Assembly a = Utils.FindLoadedAssemblyRef(assemblyRef); if (a != null) return a; // It wasn't found in memory, so look on disk String rootDir = _pipeline.PipelineRootDirectory; List<String> dirsToLookIn = new List<String>(); switch (_currentComponentType) { case PipelineComponentType.AddInAdapter: // Look in contract directory and addin base directory. dirsToLookIn.Add(Path.Combine(rootDir, AddInStore.ContractsDirName)); dirsToLookIn.Add(Path.Combine(rootDir, AddInStore.AddInBasesDirName)); break; case PipelineComponentType.AddIn: dirsToLookIn.Add(Path.Combine(rootDir, AddInStore.AddInBasesDirName)); break; default: System.Diagnostics.Contracts.Contract.Assert(false); throw new InvalidOperationException("Fell through switch in assembly resolve event!"); } // ARROWHEAD START // In the LoadFrom context, assemblies we depend on in the same folder are loaded automatically. // We don't have that behavior in Arrowhead. //String addinFolder = Path.GetDirectoryName(_pipeline._addin.Location); //dirsToLookIn.Add(addinFolder); // ARROWHEAD END // Assert permission to read from addinBase folder (and maybe contracts folder). PermissionSet permissionSet = new PermissionSet(PermissionState.None); foreach (string dir in dirsToLookIn) { permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, dir)); } permissionSet.Assert(); return Utils.LoadAssemblyFrom(dirsToLookIn, assemblyRef); //Console.WriteLine("Couldn't resolve assembly {0} while loading a {1}", simpleName, _currentComponentType); }
internal System.AddIn.Contract.IContract Activate() { // Assert permission to the contracts, AddInSideAdapters, AddInViews and specific Addin directories only. PermissionSet permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.Combine(_pipeline.PipelineRootDirectory, AddInStore.ContractsDirName))); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.Combine(_pipeline.PipelineRootDirectory, AddInStore.AddInAdaptersDirName))); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.Combine(_pipeline.PipelineRootDirectory, AddInStore.AddInBasesDirName))); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.GetDirectoryName(_pipeline._addin.Location))); permissionSet.Assert(); // Let's be very deliberate about loading precisely the components we want, // instead of relying on an assembly resolve event. We may still need the // resolve event, but let's ensure we load the right files from the right // places in the right loader contexts. Assembly.LoadFrom(_pipeline._contract.Location); // only load the AddInBase in the LoadFrom context if there is no copy // of the assembly loaded already in the Load context. Otherwise there would be an InvalidCastException // when returning it to the host in the single appdomain, non direct-connect scenario, when // the HVA assembly is also used as the AddInBase assembly. // Since the reflection call to determine whether the assembly is loaded is expensive, only // do it when we are in the single-appdomain scenario. bool alreadyPresent = false; if (_usingHostAppDomain) alreadyPresent = IsAssemblyLoaded(_pipeline._addinBase._assemblyName); if (!alreadyPresent) Assembly.LoadFrom(_pipeline._addinBase.Location); Assembly addInAssembly = Assembly.LoadFrom(_pipeline._addin.Location); Assembly addinAdapterAssembly = Assembly.LoadFrom(_pipeline._addinAdapter.Location); CodeAccessPermission.RevertAssert(); // Create instances of all the interesting objects. // Either we don't need this here, or it may need to exist for the duration of // the add-in's lifetime. // // The assembly resolve event will be removed when the addin // controller's Shutdown method is run. _assemblyResolver = new ResolveEventHandler(ResolveAssembly); AppDomain.CurrentDomain.AssemblyResolve += _assemblyResolver; // Create the AddIn _currentComponentType = PipelineComponentType.AddIn; Type addinType = addInAssembly.GetType(_pipeline._addin.TypeInfo.FullName, true); Object addIn = addinType.GetConstructor(new Type[0]).Invoke(new Object[0]); System.Diagnostics.Contracts.Contract.Assert(addIn != null, "CreateInstance didn't create the add-in"); return CreateAddInAdapter(addIn, addinAdapterAssembly); }
private static bool UserHasProfile() { // Acquire permissions to read the one key we care about from the registry // Acquite permission to query the current user identity PermissionSet permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPrincipal)); permissionSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, _fullProfileListKeyName)); permissionSet.Assert(); bool userHasProfile = false; RegistryKey userProfileKey = null; try { // inspect registry and look for user profile via SID string userSid = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value; userProfileKey = Registry.LocalMachine.OpenSubKey(_profileListKeyName + @"\" + userSid); userHasProfile = userProfileKey != null; } finally { if (userProfileKey != null) userProfileKey.Close(); CodeAccessPermission.RevertAssert(); } return userHasProfile; }
private Hashtable GetStringTable(bool isHelp) { Hashtable stringTable; RegistryKey libraryKey; PermissionSet ps = new PermissionSet(PermissionState.None); ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted)); ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); ps.Assert(); if (String.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0) libraryKey = Registry.PerformanceData; else { libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, this.machineName); } try { string[] names = null; int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // In some stress situations, querying counter values from // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009 // often returns null/empty data back. We should build fault-tolerance logic to // make it more reliable because getting null back once doesn't necessarily mean // that the data is corrupted, most of the time we would get the data just fine // in subsequent tries. while (waitRetries > 0) { try { if (!isHelp) names = (string[])libraryKey.GetValue("Counter " + perfLcid); else names = (string[])libraryKey.GetValue("Explain " + perfLcid); if ((names == null) || (names.Length == 0)) { --waitRetries; if (waitSleep == 0) waitSleep = 10; else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } } else break; } catch (IOException) { // RegistryKey throws if it can't find the value. We want to return an empty table // and throw a different exception higher up the stack. names = null; break; } catch (InvalidCastException) { // Unable to cast object of type 'System.Byte[]' to type 'System.String[]'. // this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ names = null; break; } } if (names == null) stringTable = new Hashtable(); else { stringTable = new Hashtable(names.Length/2); for (int index = 0; index < (names.Length/2); ++ index) { string nameString = names[(index *2) + 1]; if (nameString == null) nameString = String.Empty; int key; if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) { if (isHelp) { // Category Help Table throw new InvalidOperationException(SR.GetString(SR.CategoryHelpCorrupt, names[index * 2])); } else { // Counter Name Table throw new InvalidOperationException(SR.GetString(SR.CounterNameCorrupt, names[index * 2])); } } stringTable[key] = nameString; } } } finally { libraryKey.Close(); } return stringTable; }
private void OnCopy(object sender, ExecutedRoutedEventArgs e) { if (HasSelection && _selectionRect.Width > 0 && _selectionRect.Height > 0) { //Copy to clipboard IDataObject dataObject; string textString = GetText(); System.Drawing.Bitmap bmp = null; bool supportImageCopy = false; if (_scope is DocumentGrid && ((DocumentGrid)_scope).DocumentViewerOwner is DocumentApplicationDocumentViewer) { // This is XPSViewer, make sure it is user initiated if (!e.UserInitiated && !HasFullTrustPermissions()) { return; } supportImageCopy = true; } else { //Outside of XPSViewer, support image copy in full trust only supportImageCopy = HasFullTrustPermissions(); } if (supportImageCopy) { bmp = GetBitmap(); } (new UIPermission(UIPermissionClipboard.AllClipboard)).Assert();//BlessedAssert try { dataObject = new DataObject(); // Order of data is irrelevant, the pasting application will determine format dataObject.SetData(DataFormats.Text, textString, true); dataObject.SetData(DataFormats.UnicodeText, textString, true); if (bmp != null) { dataObject.SetData(DataFormats.Bitmap, bmp, true); } } finally { UIPermission.RevertAssert(); } PermissionSet ps = new PermissionSet(PermissionState.None); ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter)); ps.AddPermission(new UIPermission(UIPermissionClipboard.AllClipboard)); ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); if (supportImageCopy) { CodeAccessPermission mediaAccessPermission = SecurityHelper.CreateMediaAccessPermission(null); ps.AddPermission(mediaAccessPermission); } ps.Assert(); // BlessedAssert try { Clipboard.SetDataObject(dataObject, true); } catch (System.Runtime.InteropServices.ExternalException) { // Clipboard is failed to set the data object. return; } finally { SecurityPermission.RevertAssert(); } } }
static AssemblyName GetName(Assembly assembly, bool copyName) { PermissionSet perms = new PermissionSet(PermissionState.None); perms.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); perms.Assert(); return assembly.GetName(copyName); }
void InitDynamicModule(string asmName) { // See http://blogs.msdn.com/[....]/archive/2005/02/03/366429.aspx for a simple example // of debuggable reflection-emit. Fx.Assert(dynamicModule == null, "can only be initialized once"); // create a dynamic assembly and module AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = asmName; AssemblyBuilder assemblyBuilder; // The temporary assembly needs to be Transparent. ConstructorInfo transparentCtor = typeof(SecurityTransparentAttribute).GetConstructor( Type.EmptyTypes); CustomAttributeBuilder transparent = new CustomAttributeBuilder( transparentCtor, new Object[] { }); assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run, null, true, new CustomAttributeBuilder[] { transparent }); // Mark generated code as debuggable. // See http://blogs.msdn.com/rmbyers/archive/2005/06/26/432922.aspx for explanation. Type debuggableAttributeType = typeof(DebuggableAttribute); ConstructorInfo constructorInfo = debuggableAttributeType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) }); CustomAttributeBuilder builder = new CustomAttributeBuilder(constructorInfo, new object[] { DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.Default }); assemblyBuilder.SetCustomAttribute(builder); // We need UnmanagedCode permissions because we are asking for Symbols to be emitted. // We are protecting the dynamicModule so that only Critical code modifies it. PermissionSet unmanagedCodePermissionSet = new PermissionSet(PermissionState.None); unmanagedCodePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); unmanagedCodePermissionSet.Assert(); try { dynamicModule = assemblyBuilder.DefineDynamicModule(asmName, true); // <-- pass 'true' to track debug info. } finally { CodeAccessPermission.RevertAssert(); } }
[Category ("NotWorking")] // requires imperative stack modifiers public void RevertAssert_WithAssertion () { PermissionSet ups = new PermissionSet (PermissionState.Unrestricted); ups.Assert (); PermissionSet.RevertAssert (); }
internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parameters = xmlParameters.CodeDomParameters; parameters.ReferencedAssemblies.AddRange(Imports); if (debugEnabled) { parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.TempFiles.KeepFiles = true; } PermissionSet perms = new PermissionSet(PermissionState.None); if (xmlParameters.IsNeedTempDirAccess) { perms.AddPermission(TempAssembly.FileIOPermission); } perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence)); perms.Assert(); if (parent != null && (parameters.OutputAssembly == null || parameters.OutputAssembly.Length ==0)) { string assemblyName = AssemblyNameFromOptions(parameters.CompilerOptions); if (assemblyName == null) assemblyName = GetTempAssemblyPath(parameters.TempFiles.TempDir, parent, ns); // parameters.OutputAssembly = assemblyName; } if (parameters.CompilerOptions == null || parameters.CompilerOptions.Length == 0) parameters.CompilerOptions = "/nostdlib"; else parameters.CompilerOptions += " /nostdlib"; parameters.CompilerOptions += " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; #pragma warning disable 618 parameters.Evidence = evidence; #pragma warning restore 618 CompilerResults results = null; Assembly assembly = null; try { results = codeProvider.CompileAssemblyFromSource(parameters, writer.ToString()); // check the output for errors or a certain level-1 warning (1595) if (results.Errors.Count > 0) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture))); bool foundOne = false; foreach (CompilerError e in results.Errors) { // clear filename. This makes ToString() print just error number and message. e.FileName = ""; if (!e.IsWarning || e.ErrorNumber == "CS1595") { foundOne = true; stringWriter.WriteLine(e.ToString()); } } if (foundOne) { throw new InvalidOperationException(stringWriter.ToString()); } } assembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { // try to get the user token string user = GetCurrentUser(); if (user == null || user.Length == 0) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlSerializerAccessDenied)); } else { throw new UnauthorizedAccessException(Res.GetString(Res.XmlIdentityAccessDenied, user)); } } catch (FileLoadException fle) { throw new InvalidOperationException(Res.GetString(Res.XmlSerializerCompileFailed), fle); } finally { CodeAccessPermission.RevertAssert(); } // somehow we got here without generating an assembly if (assembly == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalError)); return assembly; }
[SecuritySafeCritical] // Asserts permission to create & delete a temp file. public void Generate() { if (_resourceList == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved")); BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8); List<String> typeNames = new List<String>(); // Write out the ResourceManager header // Write out magic number bw.Write(ResourceManager.MagicNumber); // Write out ResourceManager header version number bw.Write(ResourceManager.HeaderVersionNumber); MemoryStream resMgrHeaderBlob = new MemoryStream(240); BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob); // Write out class name of IResourceReader capable of handling // this file. resMgrHeaderPart.Write(MultitargetingHelpers.GetAssemblyQualifiedName(typeof(ResourceReader),typeConverter)); // Write out class name of the ResourceSet class best suited to // handling this file. // This needs to be the same even with multi-targeting. It's the // full name -- not the ----sembly qualified name. resMgrHeaderPart.Write(ResourceManager.ResSetTypeName); resMgrHeaderPart.Flush(); // Write number of bytes to skip over to get past ResMgr header bw.Write((int)resMgrHeaderBlob.Length); // Write the rest of the ResMgr header bw.Write(resMgrHeaderBlob.GetBuffer(), 0, (int)resMgrHeaderBlob.Length); // End ResourceManager header // Write out the RuntimeResourceSet header // Version number bw.Write(RuntimeResourceSet.Version); #if RESOURCE_FILE_FORMAT_DEBUG // Write out a tag so we know whether to enable or disable // debugging support when reading the file. bw.Write("***DEBUG***"); #endif // number of resources int numResources = _resourceList.Count; if (_preserializedData != null) numResources += _preserializedData.Count; bw.Write(numResources); // Store values in temporary streams to write at end of file. int[] nameHashes = new int[numResources]; int[] namePositions = new int[numResources]; int curNameNumber = 0; MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize); BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode); // The data section can be very large, and worse yet, we can grow the byte[] used // for the data section repeatedly. When using large resources like ~100 images, // this can lead to both a fragmented large object heap as well as allocating about // 2-3x of our storage needs in extra overhead. Using a temp file can avoid this. // Assert permission to get a temp file name, which requires two permissions. // Additionally, we may be running under an account that doesn't have permission to // write to the temp directory (enforced via a Windows ACL). Fall back to a MemoryStream. Stream dataSection = null; // Either a FileStream or a MemoryStream String tempFile = null; #if FEATURE_MONO_CAS PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); permSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); #endif try { #if FEATURE_MONO_CAS permSet.Assert(); #endif tempFile = Path.GetTempFileName(); File.SetAttributes(tempFile, FileAttributes.Temporary | FileAttributes.NotContentIndexed); // Explicitly opening with FileOptions.DeleteOnClose to avoid complicated File.Delete // (safe from ----s w/ antivirus software, etc) dataSection = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose | FileOptions.SequentialScan); } catch (UnauthorizedAccessException) { // In case we're running under an account that can't access a temp directory. dataSection = new MemoryStream(); } catch (IOException) { // In case Path.GetTempFileName fails because no unique file names are available dataSection = new MemoryStream(); } finally { #if FEATURE_MONO_CAS PermissionSet.RevertAssert(); #endif } using(dataSection) { BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8); #if FEATURE_SERIALIZATION IFormatter objFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence)); #endif // FEATURE_SERIALIZATION #if RESOURCE_FILE_FORMAT_DEBUG // Write NAMES right before the names section. names.Write(new byte[] { (byte) 'N', (byte) 'A', (byte) 'M', (byte) 'E', (byte) 'S', (byte) '-', (byte) '-', (byte) '>'}); // Write DATA at the end of the name table section. data.Write(new byte[] { (byte) 'D', (byte) 'A', (byte) 'T', (byte) 'A', (byte) '-', (byte) '-', (byte)'-', (byte)'>'}); #endif // We've stored our resources internally in a Hashtable, which // makes no guarantees about the ordering while enumerating. // While we do our own sorting of the resource names based on their // hash values, that's only sorting the nameHashes and namePositions // arrays. That's all that is strictly required for correctness, // but for ease of generating a patch in the future that // modifies just .resources files, we should re-sort them. SortedList sortedResources = new SortedList(_resourceList, FastResourceComparer.Default); if (_preserializedData != null) { foreach (KeyValuePair<String, PrecannedResource> entry in _preserializedData) sortedResources.Add(entry.Key, entry.Value); } IDictionaryEnumerator items = sortedResources.GetEnumerator(); // Write resource name and position to the file, and the value // to our temporary buffer. Save Type as well. while (items.MoveNext()) { nameHashes[curNameNumber] = FastResourceComparer.HashFunction((String)items.Key); namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current); names.Write((String)items.Key); // key names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value. #if RESOURCE_FILE_FORMAT_DEBUG names.Write((byte) '*'); #endif Object value = items.Value; ResourceTypeCode typeCode = FindTypeCode(value, typeNames); // Write out type code Write7BitEncodedInt(data, (int)typeCode); // Write out value PrecannedResource userProvidedResource = value as PrecannedResource; if (userProvidedResource != null) { data.Write(userProvidedResource.Data); } else { #if FEATURE_SERIALIZATION WriteValue(typeCode, value, data, objFormatter); #else WriteValue(typeCode, value, data); #endif } #if RESOURCE_FILE_FORMAT_DEBUG data.Write(new byte[] { (byte) 'S', (byte) 'T', (byte) 'O', (byte) 'P'}); #endif } // At this point, the ResourceManager header has been written. // Finish RuntimeResourceSet header // Write size & contents of class table bw.Write(typeNames.Count); for (int i = 0; i < typeNames.Count; i++) bw.Write(typeNames[i]); // Write out the name-related items for lookup. // Note that the hash array and the namePositions array must // be sorted in parallel. Array.Sort(nameHashes, namePositions); // Prepare to write sorted name hashes (alignment fixup) // Note: For 64-bit machines, these MUST be aligned on 8 byte // boundaries! Pointers on IA64 must be aligned! And we'll // run faster on X86 machines too. bw.Flush(); int alignBytes = ((int)bw.BaseStream.Position) & 7; if (alignBytes > 0) { for (int i = 0; i < 8 - alignBytes; i++) bw.Write("PAD"[i % 3]); } // Write out sorted name hashes. // Align to 8 bytes. Contract.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned! Ack!"); #if RESOURCE_FILE_FORMAT_DEBUG bw.Write(new byte[] { (byte) 'H', (byte) 'A', (byte) 'S', (byte) 'H', (byte) 'E', (byte) 'S', (byte) '-', (byte) '>'} ); #endif foreach (int hash in nameHashes) bw.Write(hash); #if RESOURCE_FILE_FORMAT_DEBUG Console.Write("Name hashes: "); foreach(int hash in nameHashes) Console.Write(hash.ToString("x")+" "); Console.WriteLine(); #endif // Write relative positions of all the names in the file. // Note: this data is 4 byte aligned, occuring immediately // after the 8 byte aligned name hashes (whose length may // potentially be odd). Contract.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned! Ack!"); #if RESOURCE_FILE_FORMAT_DEBUG bw.Write(new byte[] { (byte) 'P', (byte) 'O', (byte) 'S', (byte) '-', (byte) '-', (byte) '-', (byte) '-', (byte) '>' } ); #endif foreach (int pos in namePositions) bw.Write(pos); #if RESOURCE_FILE_FORMAT_DEBUG Console.Write("Name positions: "); foreach(int pos in namePositions) Console.Write(pos.ToString("x")+" "); Console.WriteLine(); #endif // Flush all BinaryWriters to their underlying streams. bw.Flush(); names.Flush(); data.Flush(); // Write offset to data section int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length); startOfDataSection += 4; // We're writing an int to store this data, adding more bytes to the header BCLDebug.Log("RESMGRFILEFORMAT", "Generate: start of DataSection: 0x" + startOfDataSection.ToString("x", CultureInfo.InvariantCulture) + " nameSection length: " + nameSection.Length); bw.Write(startOfDataSection); // Write name section. bw.Write(nameSection.GetBuffer(), 0, (int)nameSection.Length); names.Close(); // Write data section. Contract.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!"); dataSection.Position = 0; dataSection.CopyTo(bw.BaseStream); data.Close(); } // using(dataSection) <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose bw.Flush(); // Indicate we've called Generate _resourceList = null; }
private void DecodeSerializedEvidence( Evidence evidence, byte[] serializedEvidence ) { MemoryStream ms = new MemoryStream( serializedEvidence ); BinaryFormatter formatter = new BinaryFormatter(); Evidence asmEvidence = null; PermissionSet permSet = new PermissionSet( false ); permSet.SetPermission( new SecurityPermission( SecurityPermissionFlag.SerializationFormatter ) ); permSet.PermitOnly(); permSet.Assert(); try { asmEvidence = (Evidence)formatter.Deserialize( ms ); } catch (Exception) { } if (asmEvidence != null) { // Any evidence from the serialized input must: // 1. be placed in the assembly list since it is unverifiable. // 2. not be a built in class used as evidence (e.g. Zone, Site, URL, etc.) IEnumerator enumerator = asmEvidence.GetAssemblyEnumerator(); while (enumerator.MoveNext()) { Object obj = enumerator.Current; if (!(obj is Zone || obj is Site || obj is Url || obj is StrongName || obj is PermissionRequestEvidence)) evidence.AddAssembly( obj ); } } }
public void Assert_NonCasPermission () { PermissionSet ps = new PermissionSet (PermissionState.None); ps.AddPermission (new PrincipalPermission (PermissionState.None)); Assert.IsTrue (ps.ContainsNonCodeAccessPermissions (), "ContainsNonCodeAccessPermissions"); Assert.AreEqual (1, ps.Count, "Count"); ps.Assert (); // it's simply ignored }
private Cursor GetCursor(int cursorID) { Invariant.Assert(cursorID == c_SPLIT || cursorID == c_SPLITOPEN, "incorrect cursor type"); Cursor cursor = null; System.IO.Stream stream = null; System.Reflection.Assembly assembly = this.GetType().Assembly; if (cursorID == c_SPLIT) { stream = assembly.GetManifestResourceStream("split.cur"); } else if (cursorID == c_SPLITOPEN) { stream = assembly.GetManifestResourceStream("splitopen.cur"); } Debug.Assert(stream != null, "stream is null"); if (stream != null) { PermissionSet permissions = new PermissionSet(null); FileIOPermission filePermission = new FileIOPermission(PermissionState.None); filePermission.AllLocalFiles = FileIOPermissionAccess.Write; permissions.AddPermission(filePermission); permissions.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); permissions.Assert(); try { cursor = new Cursor(stream); } finally { CodeAccessPermission.RevertAssert(); } } return cursor; }