/// <summary> /// Handles any errors that CreateDirectoryEx may encounter /// </summary> private static void HandleCreateDirectoryExError(string template, string target, int errorCode) { Win32Exception win32Exception = new Win32Exception(errorCode); Exception error; switch ((Win32Error)errorCode) { case Win32Error.ACCESS_DENIED: error = new UnauthorizedAccessException( string.Format("Access was denied to clone '{0}' to '{1}'.", template, target), win32Exception); break; case Win32Error.PATH_NOT_FOUND: error = new DirectoryNotFoundException( string.Format("The path '{0}' or '{1}' could not be found.", template, target), win32Exception); break; case Win32Error.SHARING_VIOLATION: error = new SharingViolationException( string.Format("The source or destination file was in use when copying '{0}' to '{1}'.", template, target), win32Exception); break; case Win32Error.ALREADY_EXISTS: //If the directory already exists don't worry about it. return; default: error = win32Exception; break; } throw error; }
/// <summary> /// Get the security level of the user account. /// </summary> /// <param name="currentPrincipal"></param> /// <returns></returns> public static SecurityLevel GetSecurityLevel() { try { if ((ConfigurationManager.AppSettings.Keys.Count > 0) && (!string.IsNullOrEmpty(AppSettings.AuthorGroupName))) { //Check if the principal for the request is member of the admin group var principal = new WindowsPrincipal(securityContext.WindowsIdentity); if (!principal.IsInRole(AppSettings.AuthorGroupName)) { string message = string.Format( AuthMessages.InvalidCredentials, securityContext.WindowsIdentity.Name, AppSettings.AuthorGroupName); var ex = new UnauthorizedAccessException(message); Logging.Log(LoggingValues.InvalidCredentials, System.Diagnostics.EventLogEntryType.Error, null, ex); throw ex; } } } catch (AppDomainUnloadedException) { return SecurityLevel.Offline; } catch { return SecurityLevel.NoAccess; } }
protected override void LogUnauthorizedAccess(string fullName, UnauthorizedAccessException ex) { this.xmlWriter.WriteStartElement("accessDenied"); this.xmlWriter.WriteAttributeString("path", fullName); this.xmlWriter.WriteAttributeString("message", ex.Message); this.xmlWriter.WriteEndElement(); }
/// <summary> /// Checks if the provided exception is considered transient in nature or not /// Transient include issues such as a single failed network attempt /// </summary> /// <param name="originalException"></param> /// <returns></returns> private static bool IsTransient(Exception originalException) { // If the exception is an HTTP request exception then assume it is transient System.UnauthorizedAccessException authException = originalException as UnauthorizedAccessException; if (authException != null) { return(true); } // If the exception is an HTTP request exception then assume it is transient HttpRequestException httpException = originalException as HttpRequestException; if (httpException != null) { return(true); } WebException webException = originalException as WebException; if (webException != null) { // If the web exception contains one of the following status values it may be transient. return(new[] { WebExceptionStatus.ConnectionClosed, WebExceptionStatus.Timeout, WebExceptionStatus.RequestCanceled }.Contains(webException.Status)); } return(false); }
void IPscxErrorHandler.HandleUnauthorizedAccessError(bool terminating, string objectName, Exception inner) { string message = string.Format(Resources.Errors.UnauthorizedAccessException, objectName); Exception exc = new UnauthorizedAccessException(message, inner); ErrorRecord errorRecord = new ErrorRecord(exc, "UnauthorizedAccess", ErrorCategory.SecurityError, objectName); ErrorHandler.HandleError(terminating, errorRecord); }
protected void EnsureAdminUser() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); SecurityIdentifier sidAdmin = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); if (!principal.IsInRole(sidAdmin)) { UnauthorizedAccessException exception = new UnauthorizedAccessException(Resources.UserIsNotAdminError); ReportTerminatingError(exception, "UnathorizedAccess", ErrorCategory.PermissionDenied); } }
/// <summary> /// Performs the operation of the handler. /// </summary> /// <param name="input">Input to the method call.</param> /// <param name="getNext">Delegate used to get the next delegate in the call handler pipeline.</param> /// <returns>Returns value from the target method, or an <see cref="UnauthorizedAccessException"/> /// if the call fails the authorization check.</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (input == null) throw new ArgumentNullException("input"); if (getNext == null) throw new ArgumentNullException("getNext"); ReplacementFormatter formatter = new MethodInvocationFormatter(input); if (!this.AuthorizationProvider.Authorize(Thread.CurrentPrincipal, formatter.Format(OperationName))) { UnauthorizedAccessException unauthorizedExeption = new UnauthorizedAccessException(Resources.AuthorizationFailed); return input.CreateExceptionMethodReturn(unauthorizedExeption); } return getNext().Invoke(input, getNext); }
/// <summary> /// Validate the user after receiving a request, and before sending any answer. /// </summary> /// <param name="request">Request object</param> /// <param name="channel">Channel object</param> /// <param name="instanceContext">Context for the request</param> /// <returns></returns> public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { var securityContext = ServiceSecurityContext.Current; //Check if the security context is valid, if null means the user didn't provide credentials. if (securityContext != null) { //Check if the user is connected anonymously if (securityContext.IsAnonymous) { Logging.Log(LoggingValues.InvalidCredentials, System.Diagnostics.EventLogEntryType.Error, null, AuthMessages.AnonymousAccess); throw new UnauthorizedAccessException(AuthMessages.AnonymousAccess); } //Get config key from the conf file, to obtain the name of the admin group we validate. if ((ConfigurationManager.AppSettings.Keys.Count > 0) && (!string.IsNullOrEmpty(AppSettings.AuthorGroupName))) { //Check if the principal for the request is member of the admin group var principal = new WindowsPrincipal(securityContext.WindowsIdentity); if (!principal.IsInRole(AppSettings.AuthorGroupName)) { string message = string.Format( AuthMessages.InvalidCredentials, securityContext.WindowsIdentity.Name, AppSettings.AuthorGroupName); var ex = new UnauthorizedAccessException(message); Logging.Log(LoggingValues.InvalidCredentials, System.Diagnostics.EventLogEntryType.Error, null, ex); throw ex; } } else { Logging.Log(LoggingValues.InvalidCredentials, System.Diagnostics.EventLogEntryType.Error, null, AuthMessages.ConfigurationMissing); throw new UnauthorizedAccessException(AuthMessages.ConfigurationMissing); } } else { Logging.Log(LoggingValues.InvalidCredentials, System.Diagnostics.EventLogEntryType.Error, null, AuthMessages.NullCredentials); throw new UnauthorizedAccessException(AuthMessages.NullCredentials); } return null; }
public ActionResult Index(int ClientID, int PortalID, string pathEnd) { string path = HttpContext.Application["KBDataPath"] + "knowledgebase\\customerData\\" + ClientID + "\\" + pathEnd.Replace("/", "\\"); try { if (!pathEnd.ToLower().StartsWith("resources")) { UnauthorizedAccessException unauthedAccessEx = new UnauthorizedAccessException(GeneralResources.ConvertCDPathError); KBCustomException kbCustExp = KBCustomException.ProcessException(unauthedAccessEx, KBOp.ConvertResourcePath, KBErrorHandler.GetMethodName(), unauthedAccessEx.Message, LogEnabled.False, new KBExceptionData("clientID", ClientID), new KBExceptionData("portalID", PortalID), new KBExceptionData("pathEnd", pathEnd), new KBExceptionData("path", path)); throw kbCustExp; } } catch (Exception ex) { KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.ConvertResourcePath, KBErrorHandler.GetMethodName(), GeneralResources.ConvertCDPathError, new KBExceptionData("clientID", ClientID), new KBExceptionData("portalID", PortalID), new KBExceptionData("pathEnd", pathEnd), new KBExceptionData("path", path)); throw kbCustExp; } return new ResponsivePortal.Models.FileResult(path); }
/// <summary> /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException. /// and in winrt and marshal APIs as Exception. /// </summary> /// <param name="errorCode"></param> /// <param name="message"></param> /// <param name="createCOMException"></param> /// <returns></returns> internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo) { if (errorCode >= 0) { return null; } Exception exception = null; bool shouldDisplayHR = false; switch (errorCode) { case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException case __HResults.COR_E_ARITHMETIC: exception = new ArithmeticException(); break; case __HResults.COR_E_ARGUMENT: case unchecked((int)0x800A01C1): case unchecked((int)0x800A01C2): case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT: exception = new ArgumentException(); if (errorCode != __HResults.COR_E_ARGUMENT) shouldDisplayHR = true; break; case __HResults.E_BOUNDS: case __HResults.COR_E_ARGUMENTOUTOFRANGE: case __HResults.ERROR_NO_UNICODE_TRANSLATION: exception = new ArgumentOutOfRangeException(); if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_ARRAYTYPEMISMATCH: exception = new ArrayTypeMismatchException(); break; case __HResults.COR_E_BADIMAGEFORMAT: case __HResults.CLDB_E_FILE_OLDVER: case __HResults.CLDB_E_INDEX_NOTFOUND: case __HResults.CLDB_E_FILE_CORRUPT: case __HResults.COR_E_NEWER_RUNTIME: case __HResults.COR_E_ASSEMBLYEXPECTED: case __HResults.ERROR_BAD_EXE_FORMAT: case __HResults.ERROR_EXE_MARKED_INVALID: case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT: case __HResults.ERROR_NOACCESS: case __HResults.ERROR_INVALID_ORDINAL: case __HResults.ERROR_INVALID_DLL: case __HResults.ERROR_FILE_CORRUPT: case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY: case __HResults.META_E_BAD_SIGNATURE: exception = new BadImageFormatException(); // Always show HR for BadImageFormatException shouldDisplayHR = true; break; case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT: exception = new FormatException(); break; // CustomAttributeFormatException case __HResults.COR_E_DATAMISALIGNED: exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here? break; case __HResults.COR_E_DIVIDEBYZERO: case __HResults.CTL_E_DIVISIONBYZERO: exception = new DivideByZeroException(); if (errorCode != __HResults.COR_E_DIVIDEBYZERO) shouldDisplayHR = true; break; case __HResults.COR_E_DLLNOTFOUND: #if ENABLE_WINRT exception = new DllNotFoundException(); #endif break; case __HResults.COR_E_DUPLICATEWAITOBJECT: exception = new ArgumentException(); break; // DuplicateWaitObjectException case __HResults.COR_E_ENDOFSTREAM: case unchecked((int)0x800A003E): exception = new System.IO.EndOfStreamException(); if (errorCode != __HResults.COR_E_ENDOFSTREAM) shouldDisplayHR = true; break; case __HResults.COR_E_TYPEACCESS: // TypeAccessException case __HResults.COR_E_ENTRYPOINTNOTFOUND: exception = new TypeLoadException(); break; // EntryPointNotFoundException case __HResults.COR_E_EXCEPTION: exception = new Exception(); break; case __HResults.COR_E_DIRECTORYNOTFOUND: case __HResults.STG_E_PATHNOTFOUND: case __HResults.CTL_E_PATHNOTFOUND: exception = new System.IO.DirectoryNotFoundException(); if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND) shouldDisplayHR = true; break; case __HResults.COR_E_FILELOAD: case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED: case __HResults.FUSION_E_LOADFROM_BLOCKED: case __HResults.FUSION_E_CACHEFILE_FAILED: case __HResults.FUSION_E_ASM_MODULE_MISSING: case __HResults.FUSION_E_INVALID_NAME: case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: case __HResults.COR_E_MODULE_HASH_CHECK_FAILED: case __HResults.FUSION_E_REF_DEF_MISMATCH: case __HResults.SECURITY_E_INCOMPATIBLE_SHARE: case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: case __HResults.SECURITY_E_UNVERIFIABLE: case __HResults.COR_E_FIXUPSINEXE: case __HResults.ERROR_TOO_MANY_OPEN_FILES: case __HResults.ERROR_SHARING_VIOLATION: case __HResults.ERROR_LOCK_VIOLATION: case __HResults.ERROR_OPEN_FAILED: case __HResults.ERROR_DISK_CORRUPT: case __HResults.ERROR_UNRECOGNIZED_VOLUME: case __HResults.ERROR_DLL_INIT_FAILED: case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: case __HResults.CORSEC_E_MISSING_STRONGNAME: case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: case __HResults.ERROR_FILE_INVALID: exception = new System.IO.FileLoadException(); shouldDisplayHR = true; break; case __HResults.COR_E_PATHTOOLONG: exception = new System.IO.PathTooLongException(); break; case __HResults.COR_E_IO: case __HResults.CTL_E_DEVICEIOERROR: case unchecked((int)0x800A793C): case unchecked((int)0x800A793D): exception = new System.IO.IOException(); if (errorCode != __HResults.COR_E_IO) shouldDisplayHR = true; break; case __HResults.ERROR_FILE_NOT_FOUND: case __HResults.ERROR_MOD_NOT_FOUND: case __HResults.ERROR_INVALID_NAME: case __HResults.CTL_E_FILENOTFOUND: case __HResults.ERROR_BAD_NET_NAME: case __HResults.ERROR_BAD_NETPATH: case __HResults.ERROR_NOT_READY: case __HResults.ERROR_WRONG_TARGET_NAME: case __HResults.INET_E_UNKNOWN_PROTOCOL: case __HResults.INET_E_CONNECTION_TIMEOUT: case __HResults.INET_E_CANNOT_CONNECT: case __HResults.INET_E_RESOURCE_NOT_FOUND: case __HResults.INET_E_OBJECT_NOT_FOUND: case __HResults.INET_E_DOWNLOAD_FAILURE: case __HResults.INET_E_DATA_NOT_AVAILABLE: case __HResults.ERROR_DLL_NOT_FOUND: case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW: case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH: case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND: exception = new System.IO.FileNotFoundException(); shouldDisplayHR = true; break; case __HResults.COR_E_FORMAT: exception = new FormatException(); break; case __HResults.COR_E_INDEXOUTOFRANGE: case unchecked((int)0x800a0009): exception = new IndexOutOfRangeException(); if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_INVALIDCAST: exception = new InvalidCastException(); break; case __HResults.COR_E_INVALIDCOMOBJECT: exception = new InvalidComObjectException(); break; case __HResults.COR_E_INVALIDOLEVARIANTTYPE: exception = new InvalidOleVariantTypeException(); break; case __HResults.COR_E_INVALIDOPERATION: case __HResults.E_ILLEGAL_STATE_CHANGE: case __HResults.E_ILLEGAL_METHOD_CALL: case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT: case __HResults.APPMODEL_ERROR_NO_PACKAGE: exception = new InvalidOperationException(); if (errorCode != __HResults.COR_E_INVALIDOPERATION) shouldDisplayHR = true; break; case __HResults.COR_E_MARSHALDIRECTIVE: exception = new MarshalDirectiveException(); break; case __HResults.COR_E_METHODACCESS: // MethodAccessException case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException case __HResults.COR_E_FIELDACCESS: case __HResults.COR_E_MEMBERACCESS: exception = new MemberAccessException(); if (errorCode != __HResults.COR_E_METHODACCESS) shouldDisplayHR = true; break; case __HResults.COR_E_MISSINGFIELD: // MissingFieldException case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException case __HResults.COR_E_MISSINGMEMBER: case unchecked((int)0x800A01CD): exception = new MissingMemberException(); break; case __HResults.COR_E_MISSINGMANIFESTRESOURCE: exception = new System.Resources.MissingManifestResourceException(); break; case __HResults.COR_E_NOTSUPPORTED: case unchecked((int)0x800A01B6): case unchecked((int)0x800A01BD): case unchecked((int)0x800A01CA): case unchecked((int)0x800A01CB): exception = new NotSupportedException(); if (errorCode != __HResults.COR_E_NOTSUPPORTED) shouldDisplayHR = true; break; case __HResults.COR_E_NULLREFERENCE: exception = new NullReferenceException(); break; case __HResults.COR_E_OBJECTDISPOSED: case __HResults.RO_E_CLOSED: // No default constructor exception = new ObjectDisposedException(String.Empty); break; case __HResults.COR_E_OPERATIONCANCELED: #if ENABLE_WINRT exception = new OperationCanceledException(); #endif break; case __HResults.COR_E_OVERFLOW: case __HResults.CTL_E_OVERFLOW: exception = new OverflowException(); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: exception = new PlatformNotSupportedException(message); break; case __HResults.COR_E_RANK: exception = new RankException(); break; case __HResults.COR_E_REFLECTIONTYPELOAD: #if ENABLE_WINRT exception = new System.Reflection.ReflectionTypeLoadException(null, null); #endif break; case __HResults.COR_E_SECURITY: case __HResults.CORSEC_E_INVALID_STRONGNAME: case __HResults.CTL_E_PERMISSIONDENIED: case unchecked((int)0x800A01A3): case __HResults.CORSEC_E_INVALID_PUBLICKEY: case __HResults.CORSEC_E_SIGNATURE_MISMATCH: exception = new System.Security.SecurityException(); break; case __HResults.COR_E_SAFEARRAYRANKMISMATCH: exception = new SafeArrayRankMismatchException(); break; case __HResults.COR_E_SAFEARRAYTYPEMISMATCH: exception = new SafeArrayTypeMismatchException(); break; case __HResults.COR_E_SERIALIZATION: exception = new System.Runtime.Serialization.SerializationException(message); break; case __HResults.COR_E_SYNCHRONIZATIONLOCK: exception = new System.Threading.SynchronizationLockException(); break; case __HResults.COR_E_TARGETINVOCATION: exception = new System.Reflection.TargetInvocationException(null); break; case __HResults.COR_E_TARGETPARAMCOUNT: exception = new System.Reflection.TargetParameterCountException(); break; case __HResults.COR_E_TYPEINITIALIZATION: exception = InteropExtensions.CreateTypeInitializationException(message); break; case __HResults.COR_E_TYPELOAD: case __HResults.RO_E_METADATA_NAME_NOT_FOUND: case __HResults.CLR_E_BIND_TYPE_NOT_FOUND: exception = new TypeLoadException(); if (errorCode != __HResults.COR_E_TYPELOAD) shouldDisplayHR = true; break; case __HResults.COR_E_UNAUTHORIZEDACCESS: case __HResults.CTL_E_PATHFILEACCESSERROR: case unchecked((int)0x800A014F): exception = new UnauthorizedAccessException(); shouldDisplayHR = true; break; case __HResults.COR_E_VERIFICATION: exception = new System.Security.VerificationException(); break; case __HResults.E_NOTIMPL: exception = new NotImplementedException(); break; case __HResults.E_OUTOFMEMORY: case __HResults.CTL_E_OUTOFMEMORY: case unchecked((int)0x800A7919): exception = new OutOfMemoryException(); if (errorCode != __HResults.E_OUTOFMEMORY) shouldDisplayHR = true; break; #if ENABLE_WINRT case __HResults.E_XAMLPARSEFAILED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTAVAILABLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTENABLED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_LAYOUTCYCLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; #endif // ENABLE_WINRT case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException case __HResults.COR_E_APPLICATION: // ApplicationException case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException case __HResults.COR_E_CODECONTRACTFAILED: // ContractException case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException case __HResults.CORSEC_E_CRYPTO: // CryptographicException case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException case __HResults.COR_E_REMOTING: // RemotingException case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException case __HResults.COR_E_SERVER: // ServerException case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException case __HResults.COR_E_SYSTEM: // SystemException case __HResults.COR_E_TARGET: // TargetException case __HResults.COR_E_THREADABORTED: // TargetException case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException case __HResults.COR_E_THREADSTATE: // ThreadStateException case __HResults.COR_E_THREADSTART: // ThreadStartException case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException case __HResults.ISS_E_CALLER: // IsolatedStorageException case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException case __HResults.ISS_E_MACHINE: // IsolatedStorageException case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException case __HResults.E_FAIL: default: break; } if (exception == null) { if (createCOMException) { exception = new COMException(); if (errorCode != __HResults.E_FAIL) shouldDisplayHR = true; } else { exception = new Exception(); if (errorCode != __HResults.COR_E_EXCEPTION) shouldDisplayHR = true; } } bool shouldConstructMessage = false; if (hasErrorInfo) { // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if // the message is not available and do not use the shouldDisplayHR setting if (message == null) shouldConstructMessage = true; } else { // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above shouldConstructMessage = shouldDisplayHR; } if (shouldConstructMessage) { // // Append the HR into error message, just in case the app wants to look at the HR in // message to determine behavior. We didn't expose HResult property until v4.5 and // GetHRFromException has side effects so probably Message was their only choice. // This behavior is probably not exactly the same as in desktop but it is fine to append // more message at the end. In any case, having the HR in the error message are helpful // to developers. // This makes sure: // 1. We always have a HR 0xNNNNNNNN in the message // 2. Put in a nice "Exception thrown from HRESULT" message if we can // 3. Wrap it in () if there is an existing message // // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString()); message = ExternalInterop.GetMessage(errorCode); // Always make sure we have at least the HRESULT part in retail build or when the message // is empty. if (message == null) message = hrMessage; else message = message + " (" + hrMessage + ")"; } if (message != null) { // Set message explicitly rather than calling constructor because certain ctors would append a // prefix to the message and that is not what we want InteropExtensions.SetExceptionMessage(exception, message); } InteropExtensions.SetExceptionErrorCode(exception, errorCode); return exception; }
protected override void BeginProcessing() { InternalHost host = base.Host as InternalHost; if (host != null) { ConsoleHost externalHost = host.ExternalHost as ConsoleHost; if (externalHost != null) { if (!externalHost.IsTranscribing) { if (!this.isFilenameSet) { object variableValue = base.GetVariableValue("global:TRANSCRIPT", null); if (variableValue != null) { this.outFilename = (string)variableValue; } else { this.outFilename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), StringUtil.Format("PowerShell_transcript.{0:yyyyMMddHHmmss}.txt", DateTime.Now)); } } try { string str = this.ResolveFilePath(this.Path, this.isLiteralPath); if (base.ShouldProcess(this.Path)) { if (File.Exists(str)) { if (this.NoClobber && !this.Append) { string str1 = StringUtil.Format(TranscriptStrings.TranscriptFileExistsNoClobber, str, "NoClobber"); Exception unauthorizedAccessException = new UnauthorizedAccessException(str1); ErrorRecord errorRecord = new ErrorRecord(unauthorizedAccessException, "NoClobber", ErrorCategory.ResourceExists, str); base.ThrowTerminatingError(errorRecord); } FileInfo fileInfo = new FileInfo(str); if ((fileInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { if (!this.Force) { object[] objArray = new object[1]; objArray[0] = str; Exception exception = PSTraceSource.NewArgumentException(str, "TranscriptStrings", "TranscriptFileReadOnly", objArray); base.ThrowTerminatingError(new ErrorRecord(exception, "FileReadOnly", ErrorCategory.InvalidArgument, str)); } else { FileInfo attributes = fileInfo; attributes.Attributes = attributes.Attributes & (FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory | FileAttributes.Archive | FileAttributes.Device | FileAttributes.Normal | FileAttributes.Temporary | FileAttributes.SparseFile | FileAttributes.ReparsePoint | FileAttributes.Compressed | FileAttributes.Offline | FileAttributes.NotContentIndexed | FileAttributes.Encrypted #if !MONO | FileAttributes.IntegrityStream | FileAttributes.NoScrubData #endif ); } } } externalHost.StartTranscribing(str, this.Append); base.WriteObject(StringUtil.Format(TranscriptStrings.TranscriptionStarted, this.Path)); } } catch (Exception exception2) { Exception exception1 = exception2; string str2 = "CannotStartTranscription"; ErrorRecord errorRecord1 = new ErrorRecord(PSTraceSource.NewInvalidOperationException(exception1, "TranscriptStrings", str2, new object[0]), str2, ErrorCategory.InvalidOperation, null); base.ThrowTerminatingError(errorRecord1); } return; } else { throw new InvalidOperationException(TranscriptStrings.TranscriptionInProgress); } } else { throw new PSNotSupportedException(StringUtil.Format(TranscriptStrings.HostDoesNotSupportTranscript, new object[0])); } } else { throw new PSNotSupportedException(StringUtil.Format(TranscriptStrings.HostDoesNotSupportTranscript, new object[0])); } }
private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) { int error; RawSecurityDescriptor rawSD; if (createByName && name == null) { throw new ArgumentNullException(nameof(name)); } else if (!createByName && handle == null) { throw new ArgumentNullException(nameof(handle)); } error = Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out rawSD); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (exceptionFromErrorCode != null) { exception = exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_PARAMETER) { exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException( SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = (name == null ? new FileNotFoundException() : new FileNotFoundException(name)); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error)); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } return new CommonSecurityDescriptor(isContainer, false /* isDS */, rawSD, true); }
// // Attempts to persist the security descriptor onto the object // private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { WriteLock(); try { int error; SecurityInfos securityInfo = 0; SecurityIdentifier owner = null, group = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null) { securityInfo |= SecurityInfos.Owner; owner = _securityDescriptor.Owner; } if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null) { securityInfo |= SecurityInfos.Group; group = _securityDescriptor.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { securityInfo |= SecurityInfos.SystemAcl; if (_securityDescriptor.IsSystemAclPresent && _securityDescriptor.SystemAcl != null && _securityDescriptor.SystemAcl.Count > 0) { sacl = _securityDescriptor.SystemAcl; } else { sacl = null; } if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl); } } if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent) { securityInfo |= SecurityInfos.DiscretionaryAcl; // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl) { dacl = null; } else { dacl = _securityDescriptor.DiscretionaryAcl; } if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl); } } if (securityInfo == 0) { // // Nothing to persist // return; } error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (_exceptionFromErrorCode != null) { exception = _exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException( SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_INVALID_HANDLE) { exception = new NotSupportedException(SR.AccessControl_InvalidHandle); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error)); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } // // Everything goes well, let us clean the modified flags. // We are in proper write lock, so just go ahead // this.OwnerModified = false; this.GroupModified = false; this.AccessRulesModified = false; this.AuditRulesModified = false; } finally { WriteUnlock(); } }
internal static void SetAccessControlExtracted(FileSystemSecurity security, string name) { //security.WriteLock(); AccessControlSections includeSections = AccessControlSections.Audit | AccessControlSections.Owner | AccessControlSections.Group; SecurityInfos securityInfo = (SecurityInfos)0; SecurityIdentifier owner = null; SecurityIdentifier group = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; if ((includeSections & AccessControlSections.Owner) != AccessControlSections.None) { owner = (SecurityIdentifier)security.GetOwner(typeof(SecurityIdentifier)); if (owner != null) { securityInfo = securityInfo | SecurityInfos.Owner; } } if ((includeSections & AccessControlSections.Group) != AccessControlSections.None) { @group = (SecurityIdentifier)security.GetGroup(typeof(SecurityIdentifier)); if (@group != null) { securityInfo = securityInfo | SecurityInfos.Group; } } var securityDescriptorBinaryForm = security.GetSecurityDescriptorBinaryForm(); RawSecurityDescriptor rawSecurityDescriptor = null; bool isDiscretionaryAclPresent = false; if (securityDescriptorBinaryForm != null) { rawSecurityDescriptor = new RawSecurityDescriptor(securityDescriptorBinaryForm, 0); isDiscretionaryAclPresent = (rawSecurityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != ControlFlags.None; } if ((includeSections & AccessControlSections.Audit) != AccessControlSections.None) { securityInfo = securityInfo | SecurityInfos.SystemAcl; sacl = null; if (rawSecurityDescriptor != null) { var isSystemAclPresent = (rawSecurityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != ControlFlags.None; if (isSystemAclPresent && rawSecurityDescriptor.SystemAcl != null && rawSecurityDescriptor.SystemAcl.Count > 0) { // are all system acls on a file not a container? const bool notAContainer = false; const bool notADirectoryObjectACL = false; sacl = new SystemAcl(notAContainer, notADirectoryObjectACL, rawSecurityDescriptor.SystemAcl); } securityInfo = (SecurityInfos)(((rawSecurityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) == ControlFlags.None ? (uint)securityInfo | UnprotectedSystemAcl : (uint)securityInfo | ProtectedSystemAcl)); } } if ((includeSections & AccessControlSections.Access) != AccessControlSections.None && isDiscretionaryAclPresent) { securityInfo = securityInfo | SecurityInfos.DiscretionaryAcl; dacl = null; if (rawSecurityDescriptor != null) { //if (!this._securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl) { dacl = new DiscretionaryAcl(false, false, rawSecurityDescriptor.DiscretionaryAcl); } securityInfo = (SecurityInfos)(((rawSecurityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) == ControlFlags.None ? (uint)securityInfo | UnprotectedDiscretionaryAcl : (uint)securityInfo | ProtectedDiscretionaryAcl)); } } if (securityInfo == 0) return; int errorNum = SetSecurityInfo(ResourceType.FileObject, name, null, securityInfo, owner, @group, sacl, dacl); if (errorNum != 0) { Exception exception = GetExceptionFromWin32Error(errorNum, name); if (exception == null) { if (errorNum == NativeMethods.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (errorNum == NativeMethods.ERROR_INVALID_OWNER) { exception = new InvalidOperationException("Invalid owner"); } else if (errorNum == NativeMethods.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException("Invalid group"); } else if (errorNum == NativeMethods.ERROR_INVALID_NAME) { exception = new ArgumentException("Invalid name", "name"); } else if (errorNum == NativeMethods.ERROR_INVALID_HANDLE) { exception = new NotSupportedException("Invalid Handle"); } else if (errorNum == NativeMethods.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(); } else if (errorNum != NativeMethods.ERROR_NO_SECURITY_ON_OBJECT) { exception = new InvalidOperationException("Unexpected error"); } else { exception = new NotSupportedException("No associated security"); } } throw exception; } //finally //{ //security.WriteLUnlck(); //} }
private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { base.WriteLock(); try { SecurityInfos securityInformation = 0; SecurityIdentifier owner = null; SecurityIdentifier group = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; if (((includeSections & AccessControlSections.Owner) != AccessControlSections.None) && (base._securityDescriptor.Owner != null)) { securityInformation |= SecurityInfos.Owner; owner = base._securityDescriptor.Owner; } if (((includeSections & AccessControlSections.Group) != AccessControlSections.None) && (base._securityDescriptor.Group != null)) { securityInformation |= SecurityInfos.Group; group = base._securityDescriptor.Group; } if ((includeSections & AccessControlSections.Audit) != AccessControlSections.None) { securityInformation |= SecurityInfos.SystemAcl; if ((base._securityDescriptor.IsSystemAclPresent && (base._securityDescriptor.SystemAcl != null)) && (base._securityDescriptor.SystemAcl.Count > 0)) { sacl = base._securityDescriptor.SystemAcl; } else { sacl = null; } if ((base._securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != ControlFlags.None) { securityInformation |= (SecurityInfos) this.ProtectedSystemAcl; } else { securityInformation |= (SecurityInfos) this.UnprotectedSystemAcl; } } if (((includeSections & AccessControlSections.Access) != AccessControlSections.None) && base._securityDescriptor.IsDiscretionaryAclPresent) { securityInformation |= SecurityInfos.DiscretionaryAcl; if (base._securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl) { dacl = null; } else { dacl = base._securityDescriptor.DiscretionaryAcl; } if ((base._securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != ControlFlags.None) { securityInformation |= (SecurityInfos) this.ProtectedDiscretionaryAcl; } else { securityInformation |= (SecurityInfos) this.UnprotectedDiscretionaryAcl; } } if (securityInformation == 0) { return; } int errorCode = System.Security.AccessControl.Win32.SetSecurityInfo(this._resourceType, name, handle, securityInformation, owner, group, sacl, dacl); if (errorCode == 0) { goto Label_0249; } Exception exception = null; if (this._exceptionFromErrorCode != null) { exception = this._exceptionFromErrorCode(errorCode, name, handle, exceptionContext); } if (exception == null) { switch (errorCode) { case 5: exception = new UnauthorizedAccessException(); goto Label_0246; case 0x51b: exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_InvalidOwner")); goto Label_0246; case 0x51c: exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_InvalidGroup")); goto Label_0246; case 0x7b: exception = new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name"); goto Label_0246; case 6: exception = new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle")); goto Label_0246; case 2: exception = new FileNotFoundException(); goto Label_0246; case 0x546: exception = new NotSupportedException(Environment.GetResourceString("AccessControl_NoAssociatedSecurity")); goto Label_0246; } exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_UnexpectedError", new object[] { errorCode })); } Label_0246: throw exception; Label_0249: base.OwnerModified = false; base.GroupModified = false; base.AccessRulesModified = false; base.AuditRulesModified = false; } finally { base.WriteUnlock(); } }
protected override void LogUnauthorizedAccess(string fullName, UnauthorizedAccessException ex) { this.currentParent.Add(new XElement( "accessDenied" , new XAttribute("message", ex.Message))); }
private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, System.Management.Automation.Signature signature) { string str; bool flag = false; switch (this.AuthenticodePrompt(path, signature, host)) { case RunPromptDecision.NeverRun: this.UntrustPublisher(signature); str = StringUtil.Format(Authenticode.Reason_NeverRun, path); reason = new UnauthorizedAccessException(str); return false; case RunPromptDecision.DoNotRun: flag = false; str = StringUtil.Format(Authenticode.Reason_DoNotRun, path); reason = new UnauthorizedAccessException(str); return flag; case RunPromptDecision.RunOnce: return true; case RunPromptDecision.AlwaysRun: this.TrustPublisher(signature); return true; } return flag; }
private bool CheckPolicy (ExternalScriptInfo script, PSHost host, out Exception reason) { string str2; bool flag = false; reason = null; string path = script.Path; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { if (path.IndexOf ('\\') < 0) { throw PSTraceSource.NewArgumentException ("path"); } if (path.LastIndexOf ('\\') == (path.Length - 1)) { throw PSTraceSource.NewArgumentException ("path"); } } FileInfo info = new FileInfo(path); if (!info.Exists) { reason = new FileNotFoundException(path); return false; } if (!IsSupportedExtension(info.Extension)) { return true; } if (this.IsProductBinary(path)) { return true; } this.executionPolicy = SecuritySupport.GetExecutionPolicy(this.shellId); if (this.executionPolicy == ExecutionPolicy.Bypass) { return true; } SaferPolicy disallowed = SaferPolicy.Disallowed; int num = 0; bool flag2 = false; while (!flag2 && (num < 5)) { try { disallowed = SecuritySupport.GetSaferPolicy(path); flag2 = true; continue; } catch (Win32Exception) { if (num > 4) { throw; } num++; Thread.Sleep(100); continue; } } if (disallowed == SaferPolicy.Disallowed) { str2 = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path); reason = new UnauthorizedAccessException(str2); return false; } if (this.executionPolicy != ExecutionPolicy.Unrestricted) { if (this.IsLocalFile(info.FullName) && (this.executionPolicy == ExecutionPolicy.RemoteSigned)) { return true; } if ((this.executionPolicy == ExecutionPolicy.AllSigned) || (this.executionPolicy == ExecutionPolicy.RemoteSigned)) { if (string.IsNullOrEmpty(script.ScriptContents)) { str2 = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(str2); return false; } System.Management.Automation.Signature signature = this.GetSignatureWithEncodingRetry(path, script); if (signature.Status == SignatureStatus.Valid) { return (this.IsTrustedPublisher(signature, path) || this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature)); } flag = false; if (signature.Status == SignatureStatus.NotTrusted) { reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_NotTrusted, path, signature.SignerCertificate.SubjectName.Name)); return flag; } reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_Unknown, path, signature.StatusMessage)); return flag; } flag = false; bool flag3 = false; if (string.Equals(info.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase)) { string[] strArray = new string[] { Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) }; foreach (string str3 in strArray) { if (info.FullName.StartsWith(str3, StringComparison.OrdinalIgnoreCase)) { flag = true; } } if (!flag) { System.Management.Automation.Signature signature3 = this.GetSignatureWithEncodingRetry(path, script); if (signature3.Status == SignatureStatus.Valid) { if (this.IsTrustedPublisher(signature3, path)) { flag = true; } else { flag = this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature3); flag3 = true; } } } } if (!flag && !flag3) { reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_RestrictedMode, path)); } return flag; } if (this.IsLocalFile(info.FullName)) { return true; } if (string.IsNullOrEmpty(script.ScriptContents)) { str2 = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(str2); return false; } System.Management.Automation.Signature signatureWithEncodingRetry = this.GetSignatureWithEncodingRetry(path, script); if ((signatureWithEncodingRetry.Status == SignatureStatus.Valid) && this.IsTrustedPublisher(signatureWithEncodingRetry, path)) { flag = true; } if (flag) { return flag; } RunPromptDecision doNotRun = RunPromptDecision.DoNotRun; Label_0149: doNotRun = this.RemoteFilePrompt(path, host); if (doNotRun == RunPromptDecision.Suspend) { host.EnterNestedPrompt(); } switch (doNotRun) { case RunPromptDecision.RunOnce: return true; case RunPromptDecision.Suspend: goto Label_0149; } flag = false; str2 = StringUtil.Format(Authenticode.Reason_DoNotRun, path); reason = new UnauthorizedAccessException(str2); return flag; }
/// <summary> /// Handles any errors returned from CopyEx /// </summary> private static void HandleCopyExError(string source, string destination, int errorCode) { Win32Exception win32Exception = new Win32Exception(errorCode); Exception error; switch ((Win32Error)errorCode) { case Win32Error.ACCESS_DENIED: error = new UnauthorizedAccessException( string.Format("Access was denied to copy '{0}' to '{1}'.", source, destination), win32Exception); break; case Win32Error.FILE_NOT_FOUND | Win32Error.PATH_NOT_FOUND: error = new FileNotFoundException( string.Format("The file '{0}' could not be found.", source), source, win32Exception); break; case Win32Error.SHARING_VIOLATION: error = new SharingViolationException( string.Format("The source or destination file was in use when copying '{0}' to '{1}'.", source, destination), win32Exception); break; case Win32Error.DISK_FULL | Win32Error.HANDLE_DISK_FULL: error = new DiskFullException( string.Format("The destination disk for '{0}' is full.", destination), win32Exception); break; case Win32Error.REQUEST_ABORTED: return; default: error = win32Exception; break; } throw error; }
// GET: Error public ActionResult NotAuthorized() { Exception ex = new UnauthorizedAccessException(); return View("Error", ex); }
private void ProcessAccessDeniedError(UnauthorizedAccessException error) { var message = LocalizationManager.GetString("Errors.DeniedAccess", "Your computer denied Bloom access to the book. You may need technical help in setting the operating system permissions for this file."); message += Environment.NewLine + error.Message; ErrorMessagesHtml = WebUtility.HtmlEncode(message); Logger.WriteEvent("*** ERROR: " + message); _errorAlreadyContainsInstructions = true; }
protected void Page_Load(object sender, EventArgs e) { // Create safe error messages. string generalErrorMsg = "A problem has occurred on this web site. Please try again. " + "If this error continues, please contact support."; string httpErrorMsg = "An error occurred."; string unhandledErrorMsg = "The error was unhandled by application code."; string unauthorizedMsg = "Unauthorized access! You need to log in to view profile details!"; // Display safe error message. FriendlyErrorMsg.Text = generalErrorMsg; // Determine where error was handled. string errorHandler = Request.QueryString["handler"]; if (errorHandler == null) { errorHandler = "Error Page"; } // Get the last error from the server. Exception ex = Server.GetLastError(); // Get the error number passed as a querystring value. string errorMsg = Request.QueryString["msg"]; if (errorMsg == "404") { ex = new HttpException(404, httpErrorMsg, ex); FriendlyErrorMsg.Text = ex.Message; } if(errorMsg == "403") { ex = new UnauthorizedAccessException(unauthorizedMsg); FriendlyErrorMsg.Text = ex.Message; } // If the exception no longer exists, create a generic exception. if (ex == null) { ex = new Exception(unhandledErrorMsg); } // Show error details to only you (developer). LOCAL ACCESS ONLY. if (Request.IsLocal) { // Detailed Error Message. ErrorDetailedMsg.Text = ex.Message; // Show where the error was handled. ErrorHandler.Text = errorHandler; // Show local access details. DetailedErrorPanel.Visible = true; if (ex.InnerException != null) { InnerMessage.Text = ex.GetType().ToString() + "<br/>" + ex.InnerException.Message; InnerTrace.Text = ex.InnerException.StackTrace; } else { InnerMessage.Text = ex.GetType().ToString(); if (ex.StackTrace != null) { InnerTrace.Text = ex.StackTrace.ToString().TrimStart(); } } } // Log the exception. ExceptionUtility.LogException(ex, errorHandler); // Clear the error from the server. Server.ClearError(); }
/// <summary> /// Saves the current console info into a file. /// </summary> protected override void ProcessRecord() { // Get filename.. string file = GetFileName(); // if file is null or empty..prompt the user for filename if (string.IsNullOrEmpty(file)) { file = PromptUserForFile(); } // if file is still empty..write error and back out.. if (string.IsNullOrEmpty(file)) { PSArgumentException ae = PSTraceSource.NewArgumentException("file", ConsoleInfoErrorStrings.FileNameNotResolved); ThrowError(file, "FileNameNotResolved", ae, ErrorCategory.InvalidArgument); } if (WildcardPattern.ContainsWildcardCharacters(file)) { ThrowError(file, "WildCardNotSupported", PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ConsoleFileWildCardsNotSupported, file), ErrorCategory.InvalidOperation); } // Ofcourse, you cant write to a file from HKLM: etc.. string resolvedPath = ResolveProviderAndPath(file); // If resolvedPath is empty just return.. if (string.IsNullOrEmpty(resolvedPath)) { return; } // Check whether the file ends with valid extension if (!resolvedPath.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase)) { // file does not end with proper extension..create one.. resolvedPath = resolvedPath + StringLiterals.PowerShellConsoleFileExtension; } if (!ShouldProcess(this.Path)) // should this be resolvedPath? return; //check if destination file exists. if (File.Exists(resolvedPath)) { if (NoClobber) { string message = StringUtil.Format( ConsoleInfoErrorStrings.FileExistsNoClobber, resolvedPath, "NoClobber"); // prevents localization Exception uae = new UnauthorizedAccessException(message); ErrorRecord errorRecord = new ErrorRecord( uae, "NoClobber", ErrorCategory.ResourceExists, resolvedPath); // NOTE: this call will throw ThrowTerminatingError(errorRecord); } // Check if the file is read-only System.IO.FileAttributes attrib = System.IO.File.GetAttributes(resolvedPath); if ((attrib & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly) { if (Force) { RemoveFileThrowIfError(resolvedPath); // Note, we do not attempt to set read-only on the new file } else { ThrowError(file, "ConsoleFileReadOnly", PSTraceSource.NewArgumentException(file, ConsoleInfoErrorStrings.ConsoleFileReadOnly, resolvedPath), ErrorCategory.InvalidArgument); } } } try { if (this.Runspace != null) { this.Runspace.SaveAsConsoleFile(resolvedPath); } else if (InitialSessionState != null) { this.InitialSessionState.SaveAsConsoleFile(resolvedPath); } else { Dbg.Assert(false, "Both RunspaceConfiguration and InitialSessionState should not be null"); throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.CmdletNotAvailable); } } catch (PSArgumentException mae) { ThrowError(resolvedPath, "PathNotAbsolute", mae, ErrorCategory.InvalidArgument); } catch (PSArgumentNullException mane) { ThrowError(resolvedPath, "PathNull", mane, ErrorCategory.InvalidArgument); } catch (ArgumentException ae) { ThrowError(resolvedPath, "InvalidCharacetersInPath", ae, ErrorCategory.InvalidArgument); } // looks like saving succeeded. // Now try changing $console Exception e = null; try { //Update $Console variable Context.EngineSessionState.SetConsoleVariable(); } catch (ArgumentNullException ane) { e = ane; } catch (ArgumentOutOfRangeException aor) { e = aor; } catch (ArgumentException ae) { e = ae; } catch (SessionStateUnauthorizedAccessException sue) { e = sue; } catch (SessionStateOverflowException sof) { e = sof; } catch (ProviderNotFoundException pnf) { e = pnf; } catch (System.Management.Automation.DriveNotFoundException dnfe) { e = dnfe; } catch (NotSupportedException ne) { e = ne; } catch (ProviderInvocationException pin) { e = pin; } if (e != null) { throw PSTraceSource.NewInvalidOperationException(e, ConsoleInfoErrorStrings.ConsoleVariableCannotBeSet, resolvedPath); } }
protected static UserErrorModel Handle(UnauthorizedAccessException ex, string action) => new RecoverableUserError(ex, "Access denied", "Please make sure the path is writable and not in use by a running game or otherwise\n\nError info: " + ex.Message);
// public static uint ERROR_LDAP_INVALID_CREDENTIALS = 49; //fix error CS0414: Warning as Error: is assigned but its value is never used // // This method maps some common COM Hresults to // existing clr exceptions // internal static Exception GetExceptionFromCOMException(COMException e) { Exception exception; int errorCode = e.ErrorCode; string errorMessage = e.Message; // // Check if we can throw a more specific exception // if (errorCode == unchecked((int)0x80070005)) { // // Access Denied // exception = new UnauthorizedAccessException(errorMessage, e); } else if (errorCode == unchecked((int)0x800708c5) || errorCode == unchecked((int)0x80070056) || errorCode == unchecked((int)0x8007052)) { // // Password does not meet complexity requirements or old password does not match or policy restriction has been enforced. // exception = new PasswordException(errorMessage, e); } else if (errorCode == unchecked((int)0x800708b0) || errorCode == unchecked((int)0x80071392)) { // // Principal already exists // exception = new PrincipalExistsException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007052e)) { // // Logon Failure // exception = new AuthenticationException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007202f)) { // // Constraint Violation // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80072035)) { // // Unwilling to perform // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80070008)) { // // No Memory // exception = new OutOfMemoryException(); } else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f))) { exception = new PrincipalServerDownException(errorMessage, e, errorCode, null); } else { // // Wrap the exception in a generic OperationException // exception = new PrincipalOperationException(errorMessage, e, errorCode); } return exception; }
internal static Exception GetExceptionFromCOMException(COMException e) { Exception passwordException; int errorCode = e.ErrorCode; string message = e.Message; if (errorCode != -2147024891) { if (errorCode == -2147022651 || errorCode == -2147024810 || errorCode == 0x8007052) { passwordException = new PasswordException(message, e); } else { if (errorCode == -2147022672 || errorCode == -2147019886) { passwordException = new PrincipalExistsException(message, e); } else { if (errorCode != -2147023570) { if (errorCode != -2147016657) { if (errorCode != -2147016651) { if (errorCode != -2147024888) { if (errorCode == -2147016646 || errorCode == -2147016690 || errorCode == -2147016689) { passwordException = new PrincipalServerDownException(message, e, errorCode, null); } else { passwordException = new PrincipalOperationException(message, e, errorCode); } } else { passwordException = new OutOfMemoryException(); } } else { passwordException = new InvalidOperationException(message, e); } } else { passwordException = new InvalidOperationException(message, e); } } else { passwordException = new AuthenticationException(message, e); } } } } else { passwordException = new UnauthorizedAccessException(message, e); } return passwordException; }
public static UnauthorizedAccessException/*!*/ Create(RubyClass/*!*/ self, [DefaultProtocol, DefaultParameterValue(null)]MutableString message) { UnauthorizedAccessException result = new UnauthorizedAccessException(RubyExceptions.MakeMessage(ref message, "Permission denied")); RubyExceptionData.InitializeException(result, message); return result; }
private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) { RawSecurityDescriptor descriptor; if (createByName && (name == null)) { throw new ArgumentNullException("name"); } if (!createByName && (handle == null)) { throw new ArgumentNullException("handle"); } int errorCode = System.Security.AccessControl.Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out descriptor); if (errorCode == 0) { return new CommonSecurityDescriptor(isContainer, false, descriptor, true); } Exception exception = null; if (exceptionFromErrorCode != null) { exception = exceptionFromErrorCode(errorCode, name, handle, exceptionContext); } if (exception == null) { switch (errorCode) { case 5: exception = new UnauthorizedAccessException(); goto Label_0132; case 0x51b: exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_InvalidOwner")); goto Label_0132; case 0x51c: exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_InvalidGroup")); goto Label_0132; case 0x57: exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_UnexpectedError", new object[] { errorCode })); goto Label_0132; case 0x7b: exception = new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name"); goto Label_0132; case 2: exception = (name == null) ? new FileNotFoundException() : new FileNotFoundException(name); goto Label_0132; case 0x546: exception = new NotSupportedException(Environment.GetResourceString("AccessControl_NoAssociatedSecurity")); goto Label_0132; } exception = new InvalidOperationException(Environment.GetResourceString("AccessControl_UnexpectedError", new object[] { errorCode })); } Label_0132: throw exception; }
public static string ExceptionToString(System.UnauthorizedAccessException e) { return(R._("System.UnauthorizedAccessExceptionが発生しました。\r\n何度も再発する場合は、report7zを送ってください。\r\nMessage:\r\n{0}\r\n{1}", e.ToString(), e.StackTrace)); }
public void TestUnauthorizedAccessException() { UnauthorizedAccessException ex = new UnauthorizedAccessException("Unauthorized access"); this.ExecuteExceptionHandler(ex); this.mockFactory.VerifyAllExpectationsHaveBeenMet(); }
public ActionResult Download(int articleid) { int kbid = 0; string filename = string.Empty; string extension = string.Empty; try { //read portalid and clientid from route data ReadDataFromRouteData(); ArticleItem artItem = _articleManager.GetArticleItemById(articleid, null, null, 0); kbid = artItem.KnowledgeBase.Id; filename = artItem.Title; extension = artItem.Extension; System.IO.MemoryStream s = _articleManager.GetArticleFileContent(articleid, kbid, extension); if(s ==null) { string userErrorMsg = null; userErrorMsg = GeneralResources.UnAuthorizedAccess; UnauthorizedAccessException unauthedAccessEx = new UnauthorizedAccessException(GeneralResources.UnAuthorizedAccess); KBCustomException kbCustExp = KBCustomException.ProcessException(unauthedAccessEx, KBOp.RepositorySearch, KBErrorHandler.GetMethodName(), userErrorMsg, new KBExceptionData("filename", filename), new KBExceptionData("extension", extension)); throw kbCustExp; } byte[] bts = new byte[s.Length]; s.Read(bts, 0, bts.Length); return File(bts, System.Net.Mime.MediaTypeNames.Application.Octet, filename + extension); } catch (Exception ex) { KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.GetArticle, KBErrorHandler.GetMethodName(), GeneralResources.ArticleFileContentError, new KBExceptionData("articleid", articleid), new KBExceptionData("kbid", kbid), new KBExceptionData("filename", filename), new KBExceptionData("extension", extension)); throw kbCustExp; } }
protected abstract void LogUnauthorizedAccess(string fullName, UnauthorizedAccessException ex);