public static void Main() { TestMethodLevelSecurity me = new TestMethodLevelSecurity(); me.dataHolder = new MyClassWithTypeSecurity(1964, 06, 16); // Local computer zone starts with all environment permissions. me.RetrievePersonalInformation("[All permissions]"); // Deny the write permission required by the type. EnvironmentPermission epw = new EnvironmentPermission( EnvironmentPermissionAccess.Write, "PersonalInfo"); epw.Deny(); // Even though the type requires write permission, // and you do not have it; you can get the data. me.RetrievePersonalInformation( "[No write permission (demanded by type)]"); // Reset the permissions and try to get // data without read permission. CodeAccessPermission.RevertAll(); // Deny the read permission required by the method. EnvironmentPermission epr = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "PersonalInfo"); epr.Deny(); // The method requires read permission, and you // do not have it; you cannot get the data. me.RetrievePersonalInformation( "[No read permission (demanded by method)]"); }
private void SetUpInputHooks() { new UIPermission(PermissionState.Unrestricted).Assert(); IKeyboardInputSink keyboardInputSink; try { this._inputPostFilter = new HwndWrapperHook(BrowserInteropHelper.PostFilterInput); HwndSource hwndSourceWindow = base.HwndSourceWindow; hwndSourceWindow.HwndWrapper.AddHookLast(this._inputPostFilter); keyboardInputSink = hwndSourceWindow; } finally { CodeAccessPermission.RevertAll(); } new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); try { keyboardInputSink.KeyboardInputSite = new RootBrowserWindow.KeyInputSite(new SecurityCriticalData <IKeyboardInputSink>(keyboardInputSink)); } finally { CodeAccessPermission.RevertAll(); } }
static Invariant() { _strict = _strictDefaultValue; #if PRERELEASE // // Let the user override the inital value of the Strict property from the registry. // new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + RegistryKeys.WPF).Assert(); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(RegistryKeys.WPF); if (key != null) { object obj = key.GetValue("InvariantStrict"); if (obj is int) { _strict = (int)obj != 0; } } } finally { CodeAccessPermission.RevertAll(); } #endif // PRERELEASE }
/// <summary> /// read the registry to see if Win10 Dev Mode is set /// </summary> private static bool GetDevModeFromRegistry() { new RegistryPermission(RegistryPermissionAccess.Read, c_devmodeRegKeyFullPath).Assert(); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(c_devmodeRegKey); if (key != null) { using (key) { object obj = key.GetValue(c_devmodeValueName); if (obj is int) { return((int)obj != 0); } } } } finally { CodeAccessPermission.RevertAll(); } return(false); }
//let partial trust get an InputManager internal static InputManager GetInputManager() { InputManager im = null; new PermissionSet(PermissionState.Unrestricted).Assert(); try { im = InputManager.Current; } finally { CodeAccessPermission.RevertAll(); } return(im); }
//let partial trust test get an HwndSource internal static HwndSource GetHwndSource(Visual v) { HwndSource hws = null; new PermissionSet(PermissionState.Unrestricted).Assert(); try { hws = PresentationSource.FromVisual(v) as HwndSource; } finally { CodeAccessPermission.RevertAll(); } return(hws); }
internal static bool IsEnvironmentVariableSet(string value, string environmentVariable) { if (value != null) { return(IsEnvironmentValueSet(value)); } new EnvironmentPermission(EnvironmentPermissionAccess.Read, environmentVariable).Assert(); try { value = Environment.GetEnvironmentVariable(environmentVariable); } finally { CodeAccessPermission.RevertAll(); } return(IsEnvironmentValueSet(value)); }
private void Initialize(string xtcContent) { _queue = new ActionsQueue(); _xmlDoc = new XmlDocument(); XmlTextReader xmlTR = null; StringReader sReader = null; if (xtcContent == null) { xmlTR = new XmlTextReader(_xtcFilename); } else { sReader = new StringReader(xtcContent); xmlTR = new XmlTextReader(sReader); } XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; XmlReader reader = XmlReader.Create(xmlTR, settings); string dir = Directory.GetCurrentDirectory(); FileIOPermission p = new FileIOPermission(FileIOPermissionAccess.Read, dir); p.Assert(); _xmlDoc.Load(reader); CodeAccessPermission.RevertAll(); _nsmgr = new XmlNamespaceManager(_xmlDoc.NameTable); _nsmgr.AddNamespace("curr", _xmlDoc.DocumentElement.NamespaceURI); _tests = _xmlDoc.DocumentElement.ChildNodes; if (_lastCase == -1) { _lastCase = _tests.Count; } _prefix = "curr"; }
[System.Security.SecuritySafeCritical] // auto-generated public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) { throw new ArgumentNullException("path"); } Contract.EndContractBlock(); #if FEATURE_PAL if (s_BackSlash == null) { s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar, 1); } #endif // FEATURE_PAL if ((path.Length == 0) || path.Equals(s_BackSlash)) { throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_Path")); } if (isf == null) { #if FEATURE_ISOSTORE_LIGHT throw new ArgumentNullException("isf"); #else // !FEATURE_ISOSTORE_LIGHT m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); #endif // !FEATURE_ISOSTORE_LIGHT } if (isf.Disposed) { throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); } switch (mode) { case FileMode.CreateNew: // Assume new file case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file case FileMode.Open: // Open existing, else exception break; default: throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode")); } m_isf = isf; #if !FEATURE_CORECLR FileIOPermission fiop = new FileIOPermission(FileIOPermissionAccess.AllAccess, m_isf.RootDirectory); fiop.Assert(); fiop.PermitOnly(); #endif m_GivenPath = path; m_FullPath = m_isf.GetFullPath(m_GivenPath); #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT ulong oldFileSize = 0, newFileSize; bool fNewFile = false, fLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { // for finally Unlocking locked store // Cache the old file size if the file size could change // Also find if we are going to create a new file. switch (mode) { case FileMode.CreateNew: // Assume new file #if FEATURE_ISOSTORE_LIGHT // We are going to call Reserve so we need to lock the store. m_isf.Lock(ref fLock); #endif fNewFile = true; break; case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file m_isf.Lock(ref fLock); // oldFileSize needs to be // protected try { #if FEATURE_ISOSTORE_LIGHT oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)(FileInfo.UnsafeCreateFileInfo(m_FullPath).Length)); #else oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(m_FullPath)); #endif } catch (FileNotFoundException) { fNewFile = true; } catch { } break; case FileMode.Open: // Open existing, else exception break; } if (fNewFile) { m_isf.ReserveOneBlock(); } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT try { #if FEATURE_CORECLR // Since FileStream's .ctor won't do a demand, we need to do our access check here. m_isf.Demand(m_FullPath); #endif #if FEATURE_ISOSTORE_LIGHT m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true); } catch (Exception e) { #else m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true, true); } catch { #endif #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT if (fNewFile) { m_isf.UnreserveOneBlock(); } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT #if FEATURE_ISOSTORE_LIGHT // IsoStore generally does not let arbitrary exceptions flow out: a // IsolatedStorageException is thrown instead (see examples in IsolatedStorageFile.cs // Keeping this scoped to coreclr just because changing the exception type thrown is a // breaking change and that should not be introduced into the desktop without deliberation. // // Note that GetIsolatedStorageException may set InnerException. To the real exception // Today it always does this, for debug and chk builds, and for other builds asks the host // if it is okay to do so. throw IsolatedStorageFile.GetIsolatedStorageException("IsolatedStorage_Operation_ISFS", e); #else throw; #endif // FEATURE_ISOSTORE_LIGHT } #if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT // make adjustment to the Reserve / Unreserve state if ((fNewFile == false) && ((mode == FileMode.Truncate) || (mode == FileMode.Create))) { newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length); if (oldFileSize > newFileSize) { m_isf.Unreserve(oldFileSize - newFileSize); } else if (newFileSize > oldFileSize) // Can this happen ? { m_isf.Reserve(newFileSize - oldFileSize); } } } finally { if (fLock) { m_isf.Unlock(); } } #endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT #if !FEATURE_CORECLR CodeAccessPermission.RevertAll(); #endif }
public void AddAssembly(AssemblyName assemblyName) { new FileIOPermission(PermissionState.Unrestricted).Assert(); Assembly.Load(assemblyName); CodeAccessPermission.RevertAll(); }
public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) { throw new ArgumentNullException("path"); } if (s_BackSlash == null) { s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar, 1); } if ((path.Length == 0) || path.Equals(s_BackSlash)) { throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_path")); } ulong oldFileSize = 0, newFileSize; bool fNewFile = false, fLock = false; FileInfo fOld; if (isf == null) { m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); } m_isf = isf; FileIOPermission fiop = new FileIOPermission(FileIOPermissionAccess.AllAccess, m_isf.RootDirectory); fiop.Assert(); fiop.PermitOnly(); m_GivenPath = path; m_FullPath = m_isf.GetFullPath(m_GivenPath); try { // for finally Unlocking locked store // Cache the old file size if the file size could change // Also find if we are going to create a new file. switch (mode) { case FileMode.CreateNew: // Assume new file fNewFile = true; break; case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file m_isf.Lock(); // oldFileSize needs to be // protected fLock = true; // Lock succeded try { fOld = new FileInfo(m_FullPath); oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)fOld.Length); } catch (FileNotFoundException) { fNewFile = true; } catch { } break; case FileMode.Open: // Open existing, else exception break; default: throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_FileOpenMode")); } if (fNewFile) { m_isf.ReserveOneBlock(); } try { m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true); } catch { if (fNewFile) { m_isf.UnreserveOneBlock(); } throw; } // make adjustment to the Reserve / Unreserve state if ((fNewFile == false) && ((mode == FileMode.Truncate) || (mode == FileMode.Create))) { newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length); if (oldFileSize > newFileSize) { m_isf.Unreserve(oldFileSize - newFileSize); } else if (newFileSize > oldFileSize) // Can this happen ? { m_isf.Reserve(newFileSize - oldFileSize); } } } finally { if (fLock) { m_isf.Unlock(); } } CodeAccessPermission.RevertAll(); }
/// <summary> Called by the browser to serialize the entire journal or just the index of /// the current entry. The second case is when an internal Journal update needs to be /// reflected in the TravelLog. /// </summary> /// <param name="arg"> true is the entire Journal is to serialized </param> private object _GetSaveHistoryBytesDelegate(object arg) { bool entireJournal = (bool)arg; SaveHistoryReturnInfo info = new SaveHistoryReturnInfo(); // DevDiv 716414 / DevDiv2 196517 & 224724: // Checking _serviceProvider for null due to COM reentrancy issues observed by customers. // Users who perform frequent refreshes may experience shutdown while we are still starting up and are not fully initialized. // The ServiceProvider field is one of the last things to be set during initialization, so if this is null // we know that we have not finished initialization much less run the app and thus have no need to save history. if (_serviceProvider == null) { return(null); } // When we are here, the browser has just started to shut down, so we should only check // whether the application object is shutting down. if (Application.IsApplicationObjectShuttingDown == true) { return(null); } Invariant.Assert(_rbw.Value != null, "BrowserJournalingError: _rbw should not be null"); Journal journal = _rbw.Value.Journal; Invariant.Assert(journal != null, "BrowserJournalingError: Could not get internal journal for the window"); JournalEntry entry; if (entireJournal) // The application is about to be shut down... { NavigationService topNavSvc = _rbw.Value.NavigationService; try { topNavSvc.RequestCustomContentStateOnAppShutdown(); } catch (Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } } journal.PruneKeepAliveEntries(); // Since the current page is not added to the journal until it is replaced, // we add it here explicitly to the internal Journal before serializing it. entry = topNavSvc.MakeJournalEntry(JournalReason.NewContentNavigation); if (entry != null && !entry.IsAlive()) { if (entry.JEGroupState.JournalDataStreams != null) { entry.JEGroupState.JournalDataStreams.PrepareForSerialization(); } journal.UpdateCurrentEntry(entry); } else // Maybe the current content is null or a PageFunction doesn't want to be journaled. { // Then the previous navigable page, if any, should be remembered as current. entry = journal.GetGoBackEntry(); // i. _LoadHistoryStreamDelegate() has a similar special case. } } else { // (Brittle) Assumption: GetSaveHistoryBytes() is called after the current entry has // been updated in the internal journal but before the new navigation is committed. // This means journal.CurrentEntry is what was just added (or updated). // Note that it would be wrong to call topNavSvc.MakeJournalEntry() in this case because // the navigation that just took place may be in a different NavigationService (in a // frame), and here we don't know which one it is. entry = journal.CurrentEntry; // The entry may be null here when the user has selected "New Window" or pressed Ctrl+N. // In this case the browser calls us on IPersistHistory::Save and then throws that data // away. Hopefully at some point in the future that saved data will be loaded in the new // window via IPersistHistory::Load. This unusual behavior is tracked in bug 1353584. } if (entry != null) { info.title = entry.Name; info.entryId = entry.Id; } else { info.title = _rbw.Value.Title; } // We only use the base URI here because the travel log will validate a file URI when making a PIDL. // We use the URI stored in the JournalEntry, and the travel log doesn't care what the URI is, so // duplicates don't matter. info.uri = BindUriHelper.UriToString(Uri); MemoryStream saveStream = new MemoryStream(); saveStream.Seek(0, SeekOrigin.Begin); if (entireJournal) { //Save the Journal and BaseUri also. We don't need BaseUri except for the xaml case //since this is set specially for the container case (ssres scheme). Exe case //will pretty much set it to the exe path. For the xaml case it is set to the path //of the first uri(eg BaseDir\page1.xaml) that was navigated to. //BaseDir/Subdir/page2.xaml is also considered to be in the same extent and when //we navigate back to the app from a webpage, the baseUri should still be BaseDir //not BaseDir/Subdir. We were setting the BaseDir from JournalEntry.Uri but we may //end up setting BaseUri to BaseDir/Subdir which is not the same. So explicitly //persist BaseUri as well BrowserJournal browserJournal = new BrowserJournal(journal, BindUriHelper.BaseUri); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert(); try { saveStream.WriteByte(BrowserJournalHeader); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(saveStream, browserJournal); } catch (Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } // The application is shutting down and the exception would not be reported anyway. // This is here to help with debugging and failure analysis. Invariant.Assert(false, "Failed to serialize the navigation journal: " + e); } finally { CodeAccessPermission.RevertAll(); } } else { saveStream.WriteByte(JournalIdHeader); WriteInt32(saveStream, info.entryId); } info.saveByteArray = saveStream.ToArray(); ((IDisposable)saveStream).Dispose(); return(info); }
private object _GetSaveHistoryBytesDelegate(object arg) { bool flag = (bool)arg; ApplicationProxyInternal.SaveHistoryReturnInfo saveHistoryReturnInfo = new ApplicationProxyInternal.SaveHistoryReturnInfo(); if (this._serviceProvider == null) { return(null); } if (Application.IsApplicationObjectShuttingDown) { return(null); } Invariant.Assert(this._rbw.Value != null, "BrowserJournalingError: _rbw should not be null"); Journal journal = this._rbw.Value.Journal; Invariant.Assert(journal != null, "BrowserJournalingError: Could not get internal journal for the window"); JournalEntry journalEntry; if (flag) { NavigationService navigationService = this._rbw.Value.NavigationService; try { navigationService.RequestCustomContentStateOnAppShutdown(); } catch (Exception ex) { if (CriticalExceptions.IsCriticalException(ex)) { throw; } } journal.PruneKeepAliveEntries(); journalEntry = navigationService.MakeJournalEntry(JournalReason.NewContentNavigation); if (journalEntry != null && !journalEntry.IsAlive()) { if (journalEntry.JEGroupState.JournalDataStreams != null) { journalEntry.JEGroupState.JournalDataStreams.PrepareForSerialization(); } journal.UpdateCurrentEntry(journalEntry); } else { journalEntry = journal.GetGoBackEntry(); } } else { journalEntry = journal.CurrentEntry; } if (journalEntry != null) { saveHistoryReturnInfo.title = journalEntry.Name; saveHistoryReturnInfo.entryId = journalEntry.Id; } else { saveHistoryReturnInfo.title = this._rbw.Value.Title; } saveHistoryReturnInfo.uri = BindUriHelper.UriToString(this.Uri); MemoryStream memoryStream = new MemoryStream(); memoryStream.Seek(0L, SeekOrigin.Begin); if (flag) { ApplicationProxyInternal.BrowserJournal browserJournal = new ApplicationProxyInternal.BrowserJournal(journal, BindUriHelper.BaseUri); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert(); try { memoryStream.WriteByte(2); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, browserJournal); goto IL_1A6; } catch (Exception ex2) { if (CriticalExceptions.IsCriticalException(ex2)) { throw; } Invariant.Assert(false, "Failed to serialize the navigation journal: " + ex2); goto IL_1A6; } finally { CodeAccessPermission.RevertAll(); } } memoryStream.WriteByte(1); ApplicationProxyInternal.WriteInt32(memoryStream, saveHistoryReturnInfo.entryId); IL_1A6: saveHistoryReturnInfo.saveByteArray = memoryStream.ToArray(); ((IDisposable)memoryStream).Dispose(); return(saveHistoryReturnInfo); }
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) { throw new ArgumentNullException("path"); } if (path.Length == 0 || path.Equals("\\")) { throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_Path")); } if (isf == null) { this.m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); } if (isf.Disposed) { throw new ObjectDisposedException((string)null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); } switch (mode) { case FileMode.CreateNew: case FileMode.Create: case FileMode.Open: case FileMode.OpenOrCreate: case FileMode.Truncate: case FileMode.Append: this.m_isf = isf; FileIOPermission fileIoPermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, this.m_isf.RootDirectory); fileIoPermission.Assert(); fileIoPermission.PermitOnly(); this.m_GivenPath = path; this.m_FullPath = this.m_isf.GetFullPath(this.m_GivenPath); ulong num = 0; bool flag = false; bool locked = false; RuntimeHelpers.PrepareConstrainedRegions(); try { switch (mode) { case FileMode.CreateNew: flag = true; break; case FileMode.Create: case FileMode.OpenOrCreate: case FileMode.Truncate: case FileMode.Append: this.m_isf.Lock(ref locked); try { num = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(this.m_FullPath)); break; } catch (FileNotFoundException ex) { flag = true; break; } catch { break; } } if (flag) { this.m_isf.ReserveOneBlock(); } try { this.m_fs = new FileStream(this.m_FullPath, mode, access, share, bufferSize, FileOptions.None, this.m_GivenPath, true, true); } catch { if (flag) { this.m_isf.UnreserveOneBlock(); } throw; } if (!flag) { if (mode != FileMode.Truncate) { if (mode != FileMode.Create) { goto label_34; } } ulong blockSize = IsolatedStorageFile.RoundToBlockSize((ulong)this.m_fs.Length); if (num > blockSize) { this.m_isf.Unreserve(num - blockSize); } else if (blockSize > num) { this.m_isf.Reserve(blockSize - num); } } } finally { if (locked) { this.m_isf.Unlock(); } } label_34: CodeAccessPermission.RevertAll(); break; default: throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode")); } }