private FileSystemEnumerableIterator(string fullPath, string normalizedSearchPath, string searchCriteria, string userPath, SearchOption searchOption, SearchResultHandler <TSource> resultHandler, bool checkHost) { this.fullPath = fullPath; this.normalizedSearchPath = normalizedSearchPath; this.searchCriteria = searchCriteria; this._resultHandler = resultHandler; this.userPath = userPath; this.searchOption = searchOption; this._checkHost = checkHost; this.searchStack = new List <Directory.SearchData>(); if (searchCriteria != null) { if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { FileIOPermission.EmulateFileIOPermissionChecks(fullPath); FileIOPermission.EmulateFileIOPermissionChecks(normalizedSearchPath); } else { new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new string[] { Directory.GetDemandDir(fullPath, true), Directory.GetDemandDir(normalizedSearchPath, true) }, false, false).Demand(); } this.searchData = new Directory.SearchData(normalizedSearchPath, userPath, searchOption); this.CommonInit(); return; } this.empty = true; }
private static void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility) { if (owner == null) { throw new ArgumentNullException("owner"); } RuntimeType underlyingSystemType = owner as RuntimeType; if (underlyingSystemType == null) { underlyingSystemType = owner.UnderlyingSystemType as RuntimeType; } if (underlyingSystemType == null) { throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType")); } RuntimeType callerType = RuntimeMethodHandle.GetCallerType(ref stackMark); if (skipVisibility) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); } else if (callerType != underlyingSystemType) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); } if (underlyingSystemType.Assembly != callerType.Assembly) { CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, owner.Assembly.PermissionSet); } }
internal static CompressedStack GetCompressedStack(ref StackCrawlMark stackMark) { CompressedStack cs; CompressedStack innerCS = null; if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { cs = new CompressedStack(null); } else if (CodeAccessSecurityEngine.AllDomainsHomogeneousWithNoStackModifiers()) { cs = new CompressedStack(null); cs.m_pls = PermissionListSet.CreateCompressedState_HG(); } else { // regular stackwalking case cs = new CompressedStack(GetDelayedCompressedStack(ref stackMark)); if (cs.CompressedStackHandle != null && IsImmediateCompletionCandidate(cs.CompressedStackHandle, out innerCS)) { cs.CompleteConstruction(innerCS); DestroyDCSList(cs.CompressedStackHandle); } } return(cs); }
private static void CheckForInfrastructurePermission(RuntimeAssembly asm) { if (asm != RemotingServices.s_MscorlibAssembly) { CodeAccessSecurityEngine.CheckAssembly(asm, RemotingServices.s_RemotingInfrastructurePermission); } }
private static void CheckForInfrastructurePermission(RuntimeAssembly asm) { if (asm != ActivationServices.s_MscorlibAssembly) { SecurityPermission demand = new SecurityPermission(SecurityPermissionFlag.Infrastructure); CodeAccessSecurityEngine.CheckAssembly(asm, demand); } }
public static IDictionary GetEnvironmentVariables() { bool flag = CodeAccessSecurityEngine.QuickCheckForAllDemands(); char[] environmentCharArray = GetEnvironmentCharArray(); Hashtable hashtable = new Hashtable(20); StringBuilder builder = flag ? null : new StringBuilder(); bool flag2 = true; for (int i = 0; i < environmentCharArray.Length; i++) { int startIndex = i; while ((environmentCharArray[i] != '=') && (environmentCharArray[i] != '\0')) { i++; } if (environmentCharArray[i] != '\0') { if ((i - startIndex) == 0) { while (environmentCharArray[i] != '\0') { i++; } } else { string str = new string(environmentCharArray, startIndex, i - startIndex); i++; int num3 = i; while (environmentCharArray[i] != '\0') { i++; } string str2 = new string(environmentCharArray, num3, i - num3); hashtable[str] = str2; if (!flag) { if (flag2) { flag2 = false; } else { builder.Append(';'); } builder.Append(str); } } } } if (!flag) { new EnvironmentPermission(EnvironmentPermissionAccess.Read, builder.ToString()).Demand(); } return(hashtable); }
private static void CheckForInfrastructurePermission(RuntimeAssembly asm) { if (!((Assembly)asm != ActivationServices.s_MscorlibAssembly)) { return; } SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.Infrastructure); CodeAccessSecurityEngine.CheckAssembly(asm, (CodeAccessPermission)securityPermission); }
[System.Security.SecurityCritical] // auto-generated private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility) { if (m == null) { throw new ArgumentNullException("m"); } Contract.EndContractBlock(); RuntimeModule rtModule; ModuleBuilder mb = m as ModuleBuilder; if (mb != null) { rtModule = mb.InternalModule; } else { rtModule = m as RuntimeModule; } if (rtModule == null) { throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), "m"); } // The user cannot explicitly use this assembly if (rtModule == s_anonymouslyHostedDynamicMethodsModule) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), "m"); } // ask for member access if skip visibility if (skipVisibility) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); } #if !FEATURE_CORECLR // ask for control evidence if outside of the caller assembly RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark); m_creatorAssembly = callingType.GetRuntimeAssembly(); if (m.Assembly != m_creatorAssembly) { // Demand the permissions of the assembly where the DynamicMethod will live CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, m.Assembly.PermissionSet); } #else //FEATURE_CORECLR #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); #pragma warning restore 618 #endif //FEATURE_CORECLR }
public static CompressedStack GetCompressedStack() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (SecurityManager.SecurityEnabled) { return(new CompressedStack(CodeAccessSecurityEngine.GetDelayedCompressedStack(ref stackMark))); } else { return(new CompressedStack((IntPtr)0)); } }
[System.Security.SecurityCritical] // auto-generated private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility) { if (owner == null) { throw new ArgumentNullException("owner"); } RuntimeType rtOwner = owner as RuntimeType; if (rtOwner == null) { rtOwner = owner.UnderlyingSystemType as RuntimeType; } if (rtOwner == null) { throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType")); } // get the type the call is coming from RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark); // ask for member access if skip visibility if (skipVisibility) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); } else { // if the call is not coming from the same class ask for member access if (callingType != rtOwner) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); } } #if !FEATURE_CORECLR m_creatorAssembly = callingType.GetRuntimeAssembly(); // ask for control evidence if outside of the caller module if (rtOwner.Assembly != m_creatorAssembly) { // Demand the permissions of the assembly where the DynamicMethod will live CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, owner.Assembly.PermissionSet); } #else //FEATURE_CORECLR #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); #pragma warning restore 618 #endif //FEATURE_CORECLR }
unsafe public NativeOverlapped *Pack(IOCompletionCallback iocb) { NativeOverlapped *nativeOverlappedPtr = AllocNativeOverlapped(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (SecurityManager.SecurityEnabled) { (*nativeOverlappedPtr).ReservedCOR3 = CodeAccessSecurityEngine.GetDelayedCompressedStack(ref stackMark); } else { (*nativeOverlappedPtr).ReservedCOR3 = (IntPtr)null; } PackCore(nativeOverlappedPtr, iocb); return(nativeOverlappedPtr); }
[System.Security.SecurityCritical] // auto-generated internal static CompressedStack GetCompressedStack(ref StackCrawlMark stackMark) { CompressedStack cs; CompressedStack innerCS = null; if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { cs = new CompressedStack(null); cs.CanSkipEvaluation = true; } else if (CodeAccessSecurityEngine.AllDomainsHomogeneousWithNoStackModifiers()) { // if all AppDomains on the stack are homogeneous, we don't need to walk the stack // however, we do need to capture the AppDomain stack. cs = new CompressedStack(GetDelayedCompressedStack(ref stackMark, false)); cs.m_pls = PermissionListSet.CreateCompressedState_HG(); } else { // regular stackwalking case // We want this to complete without ThreadAborts - if we're in a multiple AD callstack and an intermediate AD gets unloaded, // preventing TAs here prevents a race condition where a SafeCompressedStackHandle is created to a DCS belonging to an AD that's // gone away cs = new CompressedStack(null); RuntimeHelpers.PrepareConstrainedRegions(); try { // Empty try block to ensure no ThreadAborts in the finally block } finally { cs.CompressedStackHandle = GetDelayedCompressedStack(ref stackMark, true); if (cs.CompressedStackHandle != null && IsImmediateCompletionCandidate(cs.CompressedStackHandle, out innerCS)) { try { cs.CompleteConstruction(innerCS); } finally { DestroyDCSList(cs.CompressedStackHandle); } } } } return(cs); }
//------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ public GacIdentityPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { if (!CodeAccessSecurityEngine.DoesFullTrustMeanFullTrust()) { throw new ArgumentException(Environment.GetResourceString("Argument_UnrestrictedIdentityPermission")); } } else if (state == PermissionState.None) { } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } }
internal static DirectoryInfo CreateDirectoryInfo(Directory.SearchData searchData, ref Win32Native.WIN32_FIND_DATA findData) { string fileName = findData.cFileName; string fullPath = Path.CombineNoChecks(searchData.fullPath, fileName); if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) { // There is no need to emulate checks that FileIOPermission does if we aren't in full trust. // The paths we're getting are already tested and/or coming straight from the OS. new FileIOPermission(FileIOPermissionAccess.Read, new string[] { fullPath + "\\." }, false, false).Demand(); } DirectoryInfo di = new DirectoryInfo(fullPath, fileName); di.InitializeFrom(ref findData); return(di); }
internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates, bool needFullPath) { if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) { new FileIOPermission(access, new string[1] { fullPath }, (checkForDuplicates ? 1 : 0) != 0, (needFullPath ? 1 : 0) != 0).Demand(); } else { Path.CheckInvalidPathChars(fullPath, true); if (fullPath.Length > 2 && fullPath.IndexOf(':', 2) != -1) { throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported")); } } }
internal static FileInfo CreateFileInfo(Directory.SearchData searchData, ref Win32Native.WIN32_FIND_DATA findData) { string cFileName = findData.cFileName; string text = Path.CombineNoChecks(searchData.fullPath, cFileName); if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) { new FileIOPermission(FileIOPermissionAccess.Read, new string[] { text }, false, false).Demand(); } FileInfo fileInfo = new FileInfo(text, cFileName); fileInfo.InitializeFrom(ref findData); return(fileInfo); }
internal FileSystemEnumerableIterator(string path, string originalUserPath, string searchPattern, SearchOption searchOption, SearchResultHandler <TSource> resultHandler, bool checkHost) { this.oldMode = Win32Native.SetErrorMode(1); this.searchStack = new List <Directory.SearchData>(); string text = FileSystemEnumerableIterator <TSource> .NormalizeSearchPattern(searchPattern); if (text.Length == 0) { this.empty = true; return; } this._resultHandler = resultHandler; this.searchOption = searchOption; this.fullPath = Path.GetFullPathInternal(path); string fullSearchString = FileSystemEnumerableIterator <TSource> .GetFullSearchString(this.fullPath, text); this.normalizedSearchPath = Path.GetDirectoryName(fullSearchString); if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { FileIOPermission.EmulateFileIOPermissionChecks(this.fullPath); FileIOPermission.EmulateFileIOPermissionChecks(this.normalizedSearchPath); } else { new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new string[] { Directory.GetDemandDir(this.fullPath, true), Directory.GetDemandDir(this.normalizedSearchPath, true) }, false, false).Demand(); } this._checkHost = checkHost; this.searchCriteria = FileSystemEnumerableIterator <TSource> .GetNormalizedSearchCriteria(fullSearchString, this.normalizedSearchPath); string directoryName = Path.GetDirectoryName(text); string path2 = originalUserPath; if (directoryName != null && directoryName.Length != 0) { path2 = Path.CombineNoChecks(path2, directoryName); } this.userPath = path2; this.searchData = new Directory.SearchData(this.normalizedSearchPath, this.userPath, searchOption); this.CommonInit(); }
internal static CompressedStack GetCompressedStack(ref StackCrawlMark stackMark) { CompressedStack innerCS = (CompressedStack)null; CompressedStack compressedStack; if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { compressedStack = new CompressedStack((SafeCompressedStackHandle)null); compressedStack.CanSkipEvaluation = true; } else if (CodeAccessSecurityEngine.AllDomainsHomogeneousWithNoStackModifiers()) { compressedStack = new CompressedStack(CompressedStack.GetDelayedCompressedStack(ref stackMark, false)); compressedStack.m_pls = PermissionListSet.CreateCompressedState_HG(); } else { compressedStack = new CompressedStack((SafeCompressedStackHandle)null); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { compressedStack.CompressedStackHandle = CompressedStack.GetDelayedCompressedStack(ref stackMark, true); if (compressedStack.CompressedStackHandle != null) { if (CompressedStack.IsImmediateCompletionCandidate(compressedStack.CompressedStackHandle, out innerCS)) { try { compressedStack.CompleteConstruction(innerCS); } finally { CompressedStack.DestroyDCSList(compressedStack.CompressedStackHandle); } } } } } return(compressedStack); }
private FileSystemEnumerableIterator(String fullPath, String normalizedSearchPath, String searchCriteria, String userPath, SearchOption searchOption, SearchResultHandler <TSource> resultHandler, bool checkHost) { this.fullPath = fullPath; this.normalizedSearchPath = normalizedSearchPath; this.searchCriteria = searchCriteria; this._resultHandler = resultHandler; this.userPath = userPath; this.searchOption = searchOption; this._checkHost = checkHost; searchStack = new List <Directory.SearchData>(); if (searchCriteria != null) { if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { // Full trust, just need to validate incoming paths // (we don't need to get the demand directory as it has no impact) FileIOPermission.EmulateFileIOPermissionChecks(fullPath); FileIOPermission.EmulateFileIOPermissionChecks(normalizedSearchPath); } else { // Not full trust, need to check for rights string[] demandPaths = new string[2]; // Any illegal chars such as *, ? will be caught by FileIOPermission.HasIllegalCharacters demandPaths[0] = Directory.GetDemandDir(fullPath, true); // For filters like foo\*.cs we need to verify if the directory foo is not denied access. // Do a demand on the combined path so that we can fail early in case of deny demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true); new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand(); } searchData = new Directory.SearchData(normalizedSearchPath, userPath, searchOption); CommonInit(); } else { empty = true; } }
unsafe public static void Free(NativeOverlapped *nativeOverlappedPtr) { if (nativeOverlappedPtr == null) { throw new ArgumentNullException("nativeOverlappedPtr"); } // Debugging aid if (nativeOverlappedPtr->ReservedCOR1 == unchecked ((int)0xdeadbeef)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OverlappedFreedTwice")); } nativeOverlappedPtr->ReservedCOR1 = unchecked ((int)0xdeadbeef); #if _DEBUG nativeOverlappedPtr->InternalHigh = unchecked ((int)0xdeadbeef); nativeOverlappedPtr->InternalLow = unchecked ((int)0xdeadbeef); nativeOverlappedPtr->OffsetHigh = unchecked ((int)0xdeadbeef); nativeOverlappedPtr->OffsetLow = unchecked ((int)0xdeadbeef); nativeOverlappedPtr->EventHandle = unchecked ((int)0xdeadbeef); #endif GCHandle eeHandleForAr = (*nativeOverlappedPtr).ReservedClasslib; eeHandleForAr.__InternalFree(); (*nativeOverlappedPtr).ReservedCOR2.__InternalFree(); if (nativeOverlappedPtr->ReservedCOR3 != (IntPtr)null) { #if _DEBUG if (nativeOverlappedPtr->ReservedCOR3 == (IntPtr) unchecked ((int)0xdeadbeef)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OverlappedFreedTwice")); } #endif CodeAccessSecurityEngine.ReleaseDelayedCompressedStack(nativeOverlappedPtr->ReservedCOR3); } #if _DEBUG nativeOverlappedPtr->ReservedCOR3 = new IntPtr(unchecked ((int)0xdeadbeef)); #endif FreeNativeOverlapped(nativeOverlappedPtr); }
internal static CompressedStack GetCompressedStack(ref StackCrawlMark stackMark) { CompressedStack innerCS = null; if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { return(new CompressedStack(null) { CanSkipEvaluation = true }); } if (CodeAccessSecurityEngine.AllDomainsHomogeneousWithNoStackModifiers()) { return(new CompressedStack(GetDelayedCompressedStack(ref stackMark, false)) { m_pls = PermissionListSet.CreateCompressedState_HG() }); } CompressedStack stack = new CompressedStack(null); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { stack.CompressedStackHandle = GetDelayedCompressedStack(ref stackMark, true); if ((stack.CompressedStackHandle != null) && IsImmediateCompletionCandidate(stack.CompressedStackHandle, out innerCS)) { try { stack.CompleteConstruction(innerCS); } finally { DestroyDCSList(stack.CompressedStackHandle); } } } return(stack); }
private static void PerformSecurityCheck(System.Reflection.Module m, ref StackCrawlMark stackMark, bool skipVisibility) { RuntimeModule internalModule; if (m == null) { throw new ArgumentNullException("m"); } ModuleBuilder builder = m as ModuleBuilder; if (builder != null) { internalModule = builder.InternalModule; } else { internalModule = m as RuntimeModule; } if (internalModule == null) { throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), "m"); } if (internalModule == s_anonymouslyHostedDynamicMethodsModule) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), "m"); } if (skipVisibility) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); } RuntimeType callerType = RuntimeMethodHandle.GetCallerType(ref stackMark); if (m.Assembly != callerType.Assembly) { CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, m.Assembly.PermissionSet); } }
internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception) { StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception); if (!fNeedFileInfo) { return; } // For back compat we opt-out of using Portable PDBs before 4.7.2. See the comments in // RuntimeFeature for more details. // // Even if our compat policy for enabling the feature changes, make sure that // RuntimeFeature.IsSupported accurately encapsulates that policy. Our API contract with // tools is that we will accurately tell them whether or not Portable PDB is supported. if (!RuntimeFeature.IsSupported(RuntimeFeature.PortablePdb)) { return; } // Check if this function is being reentered because of an exception in the code below if (t_reentrancy > 0) { return; } t_reentrancy++; try { // need private reflection below + unmanaged code for the portable PDB access itself // PERF: these demands are somewhat expensive so do the quick check first. We are aiming for // ~50k traces/s at 5 frames/trace on decent 2017 era hardware to maintain rough performance // parity with 4.7 implementation that didn't have Portable PDB support if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); } if (s_getSourceLineInfo == null) { Type symbolsType = Type.GetType( "System.Diagnostics.StackTraceSymbols, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false); if (symbolsType == null) { return; } MethodInfo symbolsMethodInfo = symbolsType.GetMethod("GetSourceLineInfoWithoutCasAssert", new Type[] { typeof(string), typeof(IntPtr), typeof(int), typeof(IntPtr), typeof(int), typeof(int), typeof(int), typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType() }); // We can't take a servicing dependency that System.Core.dll has been upgraded. If for whatever // wacky reason we still have the old version of System.Core.dll fallback to the original less // performant implementation of the method. if (symbolsMethodInfo == null) { symbolsMethodInfo = symbolsType.GetMethod("GetSourceLineInfo", new Type[] { typeof(string), typeof(IntPtr), typeof(int), typeof(IntPtr), typeof(int), typeof(int), typeof(int), typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType() }); } if (symbolsMethodInfo == null) { return; } // Create an instance of System.Diagnostics.Stacktrace.Symbols object target = Activator.CreateInstance(symbolsType); // Create an instance delegate for the GetSourceLineInfo method GetSourceLineInfoDelegate getSourceLineInfo = (GetSourceLineInfoDelegate)symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target); // We could ---- with another thread. It doesn't matter if we win or lose, the losing instance will be GC'ed and all threads including this one will // use the winning instance Interlocked.CompareExchange(ref s_getSourceLineInfo, getSourceLineInfo, null); } for (int index = 0; index < iFrameCount; index++) { // If there was some reason not to try get get the symbols from the portable PDB reader like the module was // ENC or the source/line info was already retrieved, the method token is 0. if (rgiMethodToken[index] != 0) { s_getSourceLineInfo(rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index], rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index], rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]); } } } catch { } finally { t_reentrancy--; } }
private unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj) { #if FEATURE_MACL DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj; #endif // FEATURE_MACL int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && Path.IsDirectorySeparator(fullPath[length - 1])) { length--; } int lengthRoot = LongPath.GetRootLength(fullPath); // For UNC paths that are only // or /// if (length == 2 && Path.IsDirectorySeparator(fullPath[1])) { throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", path)); } List <string> stackDir = new List <string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { String dir = fullPath.Substring(0, i + 1); if (!InternalExists(dir)) // Create only the ones missing { stackDir.Add(dir); } else { somepathexists = true; } while (i > lengthRoot && fullPath[i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar) { i--; } i--; } } int count = stackDir.Count; if (stackDir.Count != 0 #if FEATURE_CAS_POLICY // All demands in full trust domains are no-ops, so skip // // The full path went through validity checks by being passed through FileIOPermissions already. // As a sub string of the full path can't fail the checks if the full path passes. && !CodeAccessSecurityEngine.QuickCheckForAllDemands() #endif ) { String[] securityList = new String[stackDir.Count]; stackDir.CopyTo(securityList, 0); for (int j = 0; j < securityList.Length; j++) { securityList[j] += "\\."; // leaf will never have a slash at the end } // Security check for all directories not present only. #if !FEATURE_PAL && FEATURE_MACL AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change; FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, control, securityList, false, false); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, securityList, false, false); #endif } // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Win32Native.SECURITY_ATTRIBUTES secAttrs = null; #if FEATURE_MACL if (dirSecurity != null) { secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); // For ACL's, get the security descriptor from the FileSecurity. byte[] sd = dirSecurity.GetSecurityDescriptorBinaryForm(); byte * bytesOnStack = stackalloc byte[sd.Length]; Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length); secAttrs.pSecurityDescriptor = bytesOnStack; } #endif bool r = true; int firstError = 0; String errorString = path; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { String name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); if (name.Length >= Path.MaxLongPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } r = Win32Native.CreateDirectory(PathInternal.EnsureExtendedPrefix(name), secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Win32Native.ERROR_ALREADY_EXISTS) { firstError = currentError; } else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (LongPathFile.InternalExists(name) || (!InternalExists(name, out currentError) && currentError == Win32Native.ERROR_ACCESS_DENIED)) { firstError = currentError; // Give the user a nice error message, but don't leak path information. try { FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, GetDemandDir(name, true), false, false); errorString = name; } catch (SecurityException) { } } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\foo") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { String root = InternalGetDirectoryRoot(fullPath); if (!InternalExists(root)) { // Extract the root from the passed in path again for security. __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, InternalGetDirectoryRoot(path)); } return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) { __Error.WinIOError(firstError, errorString); } }
public static string ExpandEnvironmentVariables(string name) { int num2; if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { return(name); } bool flag = CodeAccessSecurityEngine.QuickCheckForAllDemands(); string[] strArray = name.Split(new char[] { '%' }); StringBuilder builder = flag ? null : new StringBuilder(); int capacity = 100; StringBuilder lpDst = new StringBuilder(capacity); bool flag2 = false; for (int i = 1; i < (strArray.Length - 1); i++) { if ((strArray[i].Length == 0) || flag2) { flag2 = false; } else { lpDst.Length = 0; string lpSrc = "%" + strArray[i] + "%"; num2 = Win32Native.ExpandEnvironmentStrings(lpSrc, lpDst, capacity); if (num2 == 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } while (num2 > capacity) { capacity = num2; lpDst.Capacity = capacity; lpDst.Length = 0; num2 = Win32Native.ExpandEnvironmentStrings(lpSrc, lpDst, capacity); if (num2 == 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } if (!flag && (lpDst.ToString() != lpSrc)) { builder.Append(strArray[i]); builder.Append(';'); } } } if (!flag) { new EnvironmentPermission(EnvironmentPermissionAccess.Read, builder.ToString()).Demand(); } lpDst.Length = 0; num2 = Win32Native.ExpandEnvironmentStrings(name, lpDst, capacity); if (num2 == 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } while (num2 > capacity) { capacity = num2; lpDst.Capacity = capacity; lpDst.Length = 0; num2 = Win32Native.ExpandEnvironmentStrings(name, lpDst, capacity); if (num2 == 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } return(lpDst.ToString()); }
private unsafe static void InternalCreateDirectory(string fullPath, string path, object dirSecurityObj) { DirectorySecurity directorySecurity = (DirectorySecurity)dirSecurityObj; int num = fullPath.Length; if (num >= 2 && Path.IsDirectorySeparator(fullPath[num - 1])) { num--; } int rootLength = LongPath.GetRootLength(fullPath); if (num == 2 && Path.IsDirectorySeparator(fullPath[1])) { throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", new object[] { path })); } List <string> list = new List <string>(); bool flag = false; if (num > rootLength) { int num2 = num - 1; while (num2 >= rootLength && !flag) { string text = fullPath.Substring(0, num2 + 1); if (!LongPathDirectory.InternalExists(text)) { list.Add(text); } else { flag = true; } while (num2 > rootLength && fullPath[num2] != Path.DirectorySeparatorChar && fullPath[num2] != Path.AltDirectorySeparatorChar) { num2--; } num2--; } } int count = list.Count; if (list.Count != 0 && !CodeAccessSecurityEngine.QuickCheckForAllDemands()) { string[] array = new string[list.Count]; list.CopyTo(array, 0); for (int i = 0; i < array.Length; i++) { string[] array2 = array; int num3 = i; array2[num3] += "\\."; } AccessControlActions control = (directorySecurity == null) ? AccessControlActions.None : AccessControlActions.Change; FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, control, array, false, false); } Win32Native.SECURITY_ATTRIBUTES security_ATTRIBUTES = null; if (directorySecurity != null) { security_ATTRIBUTES = new Win32Native.SECURITY_ATTRIBUTES(); security_ATTRIBUTES.nLength = Marshal.SizeOf <Win32Native.SECURITY_ATTRIBUTES>(security_ATTRIBUTES); byte[] securityDescriptorBinaryForm = directorySecurity.GetSecurityDescriptorBinaryForm(); byte * ptr = stackalloc byte[checked (unchecked ((UIntPtr)securityDescriptorBinaryForm.Length) * 1)]; Buffer.Memcpy(ptr, 0, securityDescriptorBinaryForm, 0, securityDescriptorBinaryForm.Length); security_ATTRIBUTES.pSecurityDescriptor = ptr; } bool flag2 = true; int num4 = 0; string maybeFullPath = path; while (list.Count > 0) { string text2 = list[list.Count - 1]; list.RemoveAt(list.Count - 1); if (text2.Length >= 32767) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } flag2 = Win32Native.CreateDirectory(PathInternal.EnsureExtendedPrefix(text2), security_ATTRIBUTES); if (!flag2 && num4 == 0) { int lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error != 183) { num4 = lastWin32Error; } else if (LongPathFile.InternalExists(text2) || (!LongPathDirectory.InternalExists(text2, out lastWin32Error) && lastWin32Error == 5)) { num4 = lastWin32Error; try { FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, LongPathDirectory.GetDemandDir(text2, true), false, false); maybeFullPath = text2; } catch (SecurityException) { } } } } if (count == 0 && !flag) { string path2 = LongPathDirectory.InternalGetDirectoryRoot(fullPath); if (!LongPathDirectory.InternalExists(path2)) { __Error.WinIOError(3, LongPathDirectory.InternalGetDirectoryRoot(path)); } return; } if (!flag2 && num4 != 0) { __Error.WinIOError(num4, maybeFullPath); } }
internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler <TSource> resultHandler, bool checkHost) { Contract.Requires(path != null); Contract.Requires(originalUserPath != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Requires(resultHandler != null); oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); searchStack = new List <Directory.SearchData>(); String normalizedSearchPattern = NormalizeSearchPattern(searchPattern); if (normalizedSearchPattern.Length == 0) { empty = true; } else { _resultHandler = resultHandler; this.searchOption = searchOption; fullPath = Path.GetFullPathInternal(path); String fullSearchString = GetFullSearchString(fullPath, normalizedSearchPattern); normalizedSearchPath = Path.GetDirectoryName(fullSearchString); if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { // Full trust, just need to validate incoming paths // (we don't need to get the demand directory as it has no impact) FileIOPermission.EmulateFileIOPermissionChecks(fullPath); FileIOPermission.EmulateFileIOPermissionChecks(normalizedSearchPath); } else { // Not full trust, need to check for rights string[] demandPaths = new string[2]; // Any illegal chars such as *, ? will be caught by FileIOPermission.HasIllegalCharacters demandPaths[0] = Directory.GetDemandDir(fullPath, true); // For filters like foo\*.cs we need to verify if the directory foo is not denied access. // Do a demand on the combined path so that we can fail early in case of deny demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true); new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand(); } _checkHost = checkHost; // normalize search criteria searchCriteria = GetNormalizedSearchCriteria(fullSearchString, normalizedSearchPath); // fix up user path String searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern); String userPathTemp = originalUserPath; if (searchPatternDirName != null && searchPatternDirName.Length != 0) { userPathTemp = Path.CombineNoChecks(userPathTemp, searchPatternDirName); } this.userPath = userPathTemp; searchData = new Directory.SearchData(normalizedSearchPath, this.userPath, searchOption); CommonInit(); } }
internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception) { StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception); if (!fNeedFileInfo) { return; } if (!RuntimeFeature.IsSupported("PortablePdb")) { return; } if (StackFrameHelper.t_reentrancy > 0) { return; } StackFrameHelper.t_reentrancy++; try { if (!CodeAccessSecurityEngine.QuickCheckForAllDemands()) { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); } if (StackFrameHelper.s_getSourceLineInfo == null) { Type type = Type.GetType("System.Diagnostics.StackTraceSymbols, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false); if (type == null) { return; } MethodInfo method = type.GetMethod("GetSourceLineInfoWithoutCasAssert", new Type[] { typeof(string), typeof(IntPtr), typeof(int), typeof(IntPtr), typeof(int), typeof(int), typeof(int), typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType() }); if (method == null) { method = type.GetMethod("GetSourceLineInfo", new Type[] { typeof(string), typeof(IntPtr), typeof(int), typeof(IntPtr), typeof(int), typeof(int), typeof(int), typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType() }); } if (method == null) { return; } object target = Activator.CreateInstance(type); StackFrameHelper.GetSourceLineInfoDelegate value = (StackFrameHelper.GetSourceLineInfoDelegate)method.CreateDelegate(typeof(StackFrameHelper.GetSourceLineInfoDelegate), target); Interlocked.CompareExchange <StackFrameHelper.GetSourceLineInfoDelegate>(ref StackFrameHelper.s_getSourceLineInfo, value, null); } for (int i = 0; i < this.iFrameCount; i++) { if (this.rgiMethodToken[i] != 0) { StackFrameHelper.s_getSourceLineInfo(this.rgAssemblyPath[i], this.rgLoadedPeAddress[i], this.rgiLoadedPeSize[i], this.rgInMemoryPdbAddress[i], this.rgiInMemoryPdbSize[i], this.rgiMethodToken[i], this.rgiILOffset[i], out this.rgFilename[i], out this.rgiLineNumber[i], out this.rgiColumnNumber[i]); } } } catch { } finally { StackFrameHelper.t_reentrancy--; } }