상속: System.SystemException
예제 #1
0
        static void Main(string[] args)
        {
            var exception = new System.Security.SecurityException();

            exception.GetType().LogInheritanceHierarchy();
            // Set company as parent key element.
            const string company = "TestCompany";
            // Create subkey tree.
            var subKeyTree = $"{company}\\Applications\\TestApplication";

            // Create key with no permissions.
            CreateRegistryKey(subKeyTree, PermissionState.None);
            Logging.LineSeparator();

            // Create key with unrestricted permissions.
            CreateRegistryKey(subKeyTree, PermissionState.Unrestricted);
            Logging.LineSeparator();

            // Delete key with no permissions.
            DeleteRegistryKey(company, PermissionState.None);
            Logging.LineSeparator();

            // Delete key with unrestricted permissions.
            DeleteRegistryKey(company, PermissionState.Unrestricted);
            Logging.LineSeparator();
        }
        public X509Certificate2 GetCertificateByThumbprint(StoreLocation storeLocation, string thumbprint)
        {
            X509Store certStore = new X509Store(StoreName.My, storeLocation);
            try
            {
                try
                {
                    certStore.Open(OpenFlags.ReadOnly);
                }
                catch (Exception ex)
                {
                    var outerEx = new SecurityException(string.Format("Failed to open X509Store in '{0}'.", storeLocation.ToString()), ex);
                    throw outerEx;
                }
                

                foreach(var thisCert in certStore.Certificates)
                {
                    Console.WriteLine(thisCert.Thumbprint + "\t" + thisCert.Subject);
                }

                var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                if (certCollection == null || certCollection.Count == 0)
                {
                    throw new ArgumentException(string.Format("thumbprint '{0}' does not match any certificates in '{1}'.", thumbprint, storeLocation.ToString()));
                }
                var cert = certCollection[0];
                return cert;
            }
            finally
            {
                certStore.Close();
            }
        }
		public override void Validate(string userName, string password)
		{
			if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
			{
				throw new SecurityTokenException("Username and password required.");
			}

			if (IsValidUsingCache(userName, password))
			{
				return;
			}

			try
			{
				var isValidCredentail = IsValidCredential(userName, password);

				if (isValidCredentail)
				{
					SaveCredentialInCache(userName, password);

					return;
				}

				var exception = new SecurityException(string.Format("Credential {0} not valid.", userName));

				throw exception;
			}
			catch (Exception exception)
			{
				throw ThrowFaultAndLogException(exception);
			}
		}
예제 #4
0
		public void SetUp ()
		{
			if (!SecurityManager.SecurityEnabled)
				Assert.Ignore ("SecurityManager.SecurityEnabled is OFF");

			se = new SecurityException ();
		}
예제 #5
0
 protected override void BeginProcessing()
 {
     if (!ProcessUtil.IsRunningWithElevatedPrivileges())
     {
         var exception = new SecurityException("NServiceBus was unable to perform some infrastructure operations. You need to run this command with elevated privileges. If you are running this command from Visual Studio please close Visual Studio and re-open with elevated privileges. For more information see: http://particular.net/articles/preparing-your-machine-to-run-nservicebus");
         ThrowTerminatingError(new ErrorRecord(exception, "NotAuthorized", ErrorCategory.SecurityError, null));
     }
 }
예제 #6
0
 protected override void BeginProcessing()
 {
     var processUtil = new ProcessUtil(Host);
     if (!processUtil.IsRunningWithElevatedPrivileges())
     {
         var exception = new SecurityException("This command requires elevated privileges");
         ThrowTerminatingError(new ErrorRecord(exception, null, ErrorCategory.PermissionDenied, null));
     }
 }
        public void Should_Include_InnerException_Message_In_Message() {
            // Arrange
            var securityException = new SecurityException("Message");

            // Act
            var certificateException = new CertificateException(StoreName.TrustedPeople, StoreLocation.CurrentUser, securityException);

            // Assert
            certificateException.Message.ShouldContain("Message");
        }
 protected override void BecauseOf()
 {
     try
     {
         //CustomerCreator.UpdateCustomer(Username, _updateCustomerRequest);
     }
     catch (SecurityException exception)
     {
         _exception = exception;
     }
 }
		public void Constructor_Message () 
		{
			SecurityException se = new SecurityException ("message");
#if ! NET_1_0
			AssertNull ("GrantedSet", se.GrantedSet);
			AssertNull ("RefusedSet", se.RefusedSet);
#endif
			AssertNull ("PermissionState", se.PermissionState);
			AssertNull ("PermissionType", se.PermissionType);
			AssertEquals ("ToString()", "System.Security.SecurityException: message", se.ToString ());
		}
		public void Constructor_Empty () 
		{
			SecurityException se = new SecurityException ();
#if ! NET_1_0
			AssertNull ("GrantedSet", se.GrantedSet);
			AssertNull ("RefusedSet", se.RefusedSet);
#endif
			AssertNull ("PermissionState", se.PermissionState);
			AssertNull ("PermissionType", se.PermissionType);
			Assert ("ToString()", se.ToString ().StartsWith ("System.Security.SecurityException: "));
		}
        public void Should_Set_InnerException() {
            // Arrange
            var securityException = new SecurityException("Message");

            // Act
            var certificateException = new CertificateException(StoreName.TrustedPeople, StoreLocation.CurrentUser, securityException);

            // Assert
            certificateException.InnerException.ShouldNotBeNull();
            certificateException.InnerException.ShouldEqual(securityException);
        }
        public void Should_Have_A_Descriptive_Message() {
            // Arrange
            var securityException = new SecurityException("Message");
            var messageRegex = new Regex("Unable to access the (.+) store in the (.+) location: (.+)", RegexOptions.Compiled);

            // Act
            var certificateException = new CertificateException(StoreName.TrustedPeople, StoreLocation.CurrentUser, securityException);

            // Assert
            messageRegex.IsMatch(certificateException.Message).ShouldBeTrue();
        }
		public void Constructor_Empty () 
		{
			SecurityException se = new SecurityException ();
#if ! NET_1_0
			Assert.IsNull (se.GrantedSet, "GrantedSet");
			Assert.IsNull (se.RefusedSet, "RefusedSet");
#endif
			Assert.IsNull (se.PermissionState, "PermissionState");
			Assert.IsNull (se.PermissionType, "PermissionType");
			Assert.IsTrue (se.ToString ().StartsWith ("System.Security.SecurityException: "), "ToString()");
		}
		public void Constructor_Message () 
		{
			SecurityException se = new SecurityException ("message");
#if ! NET_1_0
			Assert.IsNull (se.GrantedSet, "GrantedSet");
			Assert.IsNull (se.RefusedSet, "RefusedSet");
#endif
			Assert.IsNull (se.PermissionState, "PermissionState");
			Assert.IsNull (se.PermissionType, "PermissionType");
			Assert.AreEqual ("System.Security.SecurityException: message", se.ToString (), "ToString()");
		}
		public void Constructor_MessageInner () 
		{
			SecurityException se = new SecurityException ("message", new Exception ());
#if ! NET_1_0
			Assert.IsNull (se.GrantedSet, "GrantedSet");
			Assert.IsNull (se.RefusedSet, "RefusedSet");
#endif
			Assert.IsNull (se.PermissionState, "PermissionState");
			Assert.IsNull (se.PermissionType, "PermissionType");
			Assert.IsTrue (se.ToString ().StartsWith ("System.Security.SecurityException: message"), "ToString().Starts");
			Assert.IsTrue ((se.ToString ().IndexOf ("System.Exception") > 0), "ToString().Include");
		}
        protected override void Context()
        {
            base.Context();

            _exceptionThrownByDomain = new SecurityException("User is not authorized to QuickSearch customers");
            CustomerService.Stub(
                x =>
                x.QuickSearchCustomers(Arg<string>.Is.Equal(Username), Arg<QuickSearchCustomersRequest>.Is.Anything))
                .Throw(_exceptionThrownByDomain);

            Logger.Stub(x => x.LogException(Arg<Exception>.Is.Anything))
                .WhenCalled(x => _exceptionPassedToLogger = x.Arguments[0] as Exception);
        }
		public void Constructor_MessageTypeState () 
		{
			SecurityException se = new SecurityException ("message", typeof (EnvironmentPermission), "mono");
#if ! NET_1_0
			Assert.IsNull (se.GrantedSet, "GrantedSet");
			Assert.IsNull (se.RefusedSet, "RefusedSet");
#endif
			Assert.AreEqual ("mono", se.PermissionState, "PermissionState");
			Assert.AreEqual (typeof (EnvironmentPermission), se.PermissionType, "PermissionType");

			Assert.IsTrue ((se.ToString ().IndexOf ("mono") > 0), "ToString().Include(mono)");
			// note: can't check for PermissionType as it's not shown with MS class lib
		}
		public void Constructor_MessageType () 
		{
			SecurityException se = new SecurityException ("message", typeof (EnvironmentPermission));
#if ! NET_1_0
			Assert.IsNull (se.GrantedSet, "GrantedSet");
			Assert.IsNull (se.RefusedSet, "RefusedSet");
#endif
			Assert.IsNull (se.PermissionState, "PermissionState");
			Assert.AreEqual (typeof (EnvironmentPermission), se.PermissionType, "PermissionType");

			Assert.IsTrue (se.ToString ().StartsWith ("System.Security.SecurityException: message"), "ToString().Starts");
			// note: can't check for PermissionType as it's not shown with MS class lib
		}
예제 #19
0
        [System.Security.SecurityCritical]  // auto-generated
#pragma warning disable 618
        private static void ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
#pragma warning restore 618
        {
            AssemblyName asmName     = null;
            Evidence     asmEvidence = null;

            if (asm != null)
            {
                // Assert here because reflection will check grants and if we fail the check,
                // there will be an infinite recursion that overflows the stack.
                PermissionSet.s_fullTrust.Assert();
                asmName = asm.GetName();
#if FEATURE_CAS_POLICY
                if (asm != Assembly.GetExecutingAssembly()) // this condition is to avoid having to marshal mscorlib's evidence (which is always in teh default domain) to the current domain
                {
                    asmEvidence = asm.Evidence;
                }
#endif // FEATURE_CAS_POLICY
            }
            throw SecurityException.MakeSecurityException(asmName, asmEvidence, granted, refused, rmh, action, demand, permThatFailed);
        }
예제 #20
0
        // Token: 0x06001DFF RID: 7679 RVA: 0x000688D8 File Offset: 0x00066AD8
        private void ToStringHelper(StringBuilder sb, string resourceString, object attr)
        {
            if (attr == null)
            {
                return;
            }
            string text = attr as string;

            if (text == null)
            {
                text = attr.ToString();
            }
            if (text.Length == 0)
            {
                return;
            }
            sb.Append(Environment.NewLine);
            sb.Append(SecurityException.GetResString(resourceString));
            sb.Append(Environment.NewLine);
            sb.Append(text);
        }
예제 #21
0
        internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, object demand, IPermission permThatFailed)
        {
            HostProtectionPermission hostProtectionPermission = permThatFailed as HostProtectionPermission;

            if (hostProtectionPermission != null)
            {
                return(new HostProtectionException(SecurityException.GetResString("HostProtection_HostProtection"), HostProtectionPermission.protectedResources, hostProtectionPermission.Resources));
            }
            string     message = "";
            MethodInfo method  = null;

            try
            {
                if (granted == null && refused == null && demand == null)
                {
                    message = SecurityException.GetResString("Security_NoAPTCA");
                }
                else if (demand != null && demand is IPermission)
                {
                    message = string.Format(CultureInfo.InvariantCulture, SecurityException.GetResString("Security_Generic"), demand.GetType().AssemblyQualifiedName);
                }
                else if (permThatFailed != null)
                {
                    message = string.Format(CultureInfo.InvariantCulture, SecurityException.GetResString("Security_Generic"), permThatFailed.GetType().AssemblyQualifiedName);
                }
                else
                {
                    message = SecurityException.GetResString("Security_GenericNoType");
                }
                method = SecurityRuntime.GetMethodInfo(rmh);
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                {
                    throw;
                }
            }
            return(new SecurityException(message, asmName, granted, refused, method, action, demand, permThatFailed, asmEvidence));
        }
예제 #22
0
 internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj) : base(SecurityException.GetResString("Arg_SecurityException"))
 {
     PermissionSet.s_fullTrust.Assert();
     base.SetErrorCode(-2146233078);
     if (grantedSetObj != null)
     {
         this.m_granted = grantedSetObj.ToXml().ToString();
     }
     if (refusedSetObj != null)
     {
         this.m_refused = refusedSetObj.ToXml().ToString();
     }
 }
예제 #23
0
 public SecurityException()
     : base(SecurityException.GetResString("Arg_SecurityException"))
 {
     this.SetErrorCode(-2146233078);
 }
예제 #24
0
 private MethodInfo getMethod()
 {
     return((MethodInfo)SecurityException.ByteArrayToObject(this.m_serializedMethodInfo));
 }
        internal bool CheckDemandInternal(CodeAccessPermission demand, PermissionToken permToken, bool createException, out Exception exception)
        {
            BCLDebug.Assert(demand != null, "demand != null");
            BCLDebug.Assert(permToken != null, "permToken != null");

            // First, find if there is a permission list of this type.

            PermissionList permList = FindPermissionList(permToken);

            if (permList != null)
            {
                // If so, check against it to determine our action.

                bool cont = permList.CheckDemandInternal(demand, createException, out exception);

                // We don't record modifiers for the unrestricted permission set in the
                // individual lists.  Therefore, permList.CheckDemandInternal may say
                // that we have to continue the stackwalk, but we know better.

                if (cont && permToken.m_isUnrestricted)
                {
                    if ((m_state & PermissionListSetState.UnrestrictedDeny) != 0)
                    {
                        if (createException)
                        {
                            exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName));
                        }
                        else
                        {
                            exception = GetStaticException();
                        }
                        return(false);
                    }
                    else
                    {
                        cont = cont && ((m_state & PermissionListSetState.UnrestrictedAssert) == 0);
                    }
                }

                return(cont);
            }
#if _DEBUG
            // Let's check to make sure we always pass demands for empty permissions.

            else if (demand.IsSubsetOf(null))
            {
                BCLDebug.Assert(false, "We should pick of empty demands before this point");
                exception = null;
                return(true);
            }
#endif
            // If the permission is not unrestricted, the lack of a permission list
            // denotes that no frame on the stack granted this permission, and therefore
            // we pass back the failure condition.

            else if (!permToken.m_isUnrestricted)
            {
                if (createException)
                {
                    exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName));
                }
                else
                {
                    exception = GetStaticException();
                }
                return(false);
            }

            // If this permission list set is not unrestricted and there is no unrestricted assert
            // then the lack of a permission list denotes that no frame on the stack granted
            // this permission, and therefore we pass back the failure condition.  If there is
            // an unrestricted assert, then we pass back success and terminate the stack walk.

            else if (!this.IsUnrestricted())
            {
                if (createException)
                {
                    exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName));
                }
                else
                {
                    exception = GetStaticException();
                }
                return(false);
            }

            // If we made it all the way through, that means that we are in the unrestricted
            // state and that this permission is encompassed in that.  If we have an unrestricted
            // assert, we are done with the state walk (return false), otherwise keep going.

            exception = null;
            return((m_state & PermissionListSetState.UnrestrictedAssert) == 0);
        }
예제 #26
0
		private static void HandleInnerException(ref RunningResults results, SecurityException ex)
		{
			results.Verdict = Verdict.SecurityException;
			results.Error = ex.ToString();
		}
예제 #27
0
        private bool HasRedirectPermission(Uri uri, ref Exception resultException)
        {
            try {
                CheckConnectPermission(uri, Async);
            }
            catch (SecurityException e) {
                resultException = new SecurityException(SR.GetString(SR.net_redirect_perm),
                    new WebException(SR.GetString(SR.net_resubmitcanceled), e,
                        WebExceptionStatus.ProtocolError, _HttpResponse));

                GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::CheckRedirectPermission", "false");
                return false;
            }

            return true;
        }
        public bool CheckSetDemandInternal(PermissionSet permSet, bool createException, out Exception exception, bool bNeedAlteredSet, out PermissionSet alteredSet)
        {
            alteredSet = null;

            BCLDebug.Assert(permSet != null, "permSet != null");

            // If the compressed stack is not unrestricted and the demand is
            // then we just throw an exception.
            if (!this.m_unrestricted && permSet.IsUnrestricted())
            {
                if (createException)
                {
                    exception = new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                }
                else
                {
                    exception = GetStaticException();
                }
                return(false);
            }


            TokenBasedSet normalAlteredSet       = null;
            TokenBasedSet unrestrictedAlteredSet = null;

            // Check the "normal" permissions since we always know we have to check them.

            bool normalContinue = CheckTokenBasedSets(this.m_normalPermSet, permSet.m_normalPermSet, false, PermissionListSetState.None, createException, out exception, bNeedAlteredSet, out normalAlteredSet);

            if (exception != null)
            {
                return(false);
            }

            bool unrestrictedContinue = CheckTokenBasedSets(this.m_unrestrictedPermSet, permSet.m_unrestrictedPermSet, m_unrestricted, m_state, createException, out exception, bNeedAlteredSet, out unrestrictedAlteredSet);

            if (exception != null)
            {
                return(false);
            }

            if ((m_state & PermissionListSetState.UnrestrictedAssert) != 0)
            {
                // If we are unrestricted, we want to terminate the stack walk based
                // on us having an unrestricted assert.

                if (bNeedAlteredSet)
                {
                    unrestrictedAlteredSet = new TokenBasedSet(1, 4);
                }
                unrestrictedContinue = false;
            }

            if (normalContinue || unrestrictedContinue)
            {
                if (!bNeedAlteredSet)
                {
                    return(true);
                }

                // If we need to continue, let's build the altered set.  We only
                // need to do this if 1) our original demand is not unrestricted
                // and 2) if we have altered token based sets.

                if (!permSet.IsUnrestricted())
                {
                    if (normalAlteredSet != null || unrestrictedAlteredSet != null)
                    {
                        alteredSet = new PermissionSet(false);

                        if (normalAlteredSet != null)
                        {
                            alteredSet.m_normalPermSet = normalAlteredSet;
                        }
                        else
                        {
                            alteredSet.m_normalPermSet = CopyTokenBasedSet(permSet.m_normalPermSet);
                        }

                        if (unrestrictedAlteredSet != null)
                        {
                            alteredSet.m_unrestrictedPermSet = unrestrictedAlteredSet;
                        }
                        else
                        {
                            alteredSet.m_unrestrictedPermSet = CopyTokenBasedSet(permSet.m_unrestrictedPermSet);
                        }

                        if (alteredSet.IsEmpty())
                        {
                            return(false);
                        }
                    }
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
 private HostProtectionException(HostProtectionResource protectedResources, HostProtectionResource demandedResources) : base(SecurityException.GetResString("HostProtection_HostProtection"))
 {
     base.SetErrorCode(-2146232768);
     this.m_protected = protectedResources;
     this.m_demanded  = demandedResources;
 }
예제 #30
0
		private void UploadStringResponseAsyncCallback (IAsyncResult result)
		{
			string data = null;
			Exception ex = null;
			bool cancel = false;
			try {
				WebResponse response = request.EndGetResponse (result);
				Stream stream = ProcessResponse (response);

				using (StreamReader sr = new StreamReader (stream, encoding, true)) {
					data = sr.ReadToEnd ();
				}
			}
			catch (WebException web) {
				cancel = (web.Status == WebExceptionStatus.RequestCanceled);
				ex = web;
			}
			catch (SecurityException se) {
				// SecurityException inside a SecurityException (not a WebException) for SL compatibility
				ex = new SecurityException (String.Empty, se);
			}
			catch (Exception e) {
				ex = new WebException ("Could not complete operation.", e, WebExceptionStatus.UnknownError, null);
			}
			finally {
				callback_data.sync_context.Post (delegate (object sender) {
					OnUploadStringCompleted (new UploadStringCompletedEventArgs (data, ex, cancel, callback_data.user_token));
				}, null);
			}
		}
예제 #31
0
        internal bool CheckDemandInternal(CodeAccessPermission demand, PermissionToken permToken, out Exception exception)
        {
            BCLDebug.Assert(demand != null, "demand != null");
            BCLDebug.Assert(permToken != null, "permToken != null");
            
            // First, find if there is a permission list of this type.

            PermissionList permList = FindPermissionList(permToken);
                
            if (permList != null)
            {
                // If so, check against it to determine our action.

                bool cont = permList.CheckDemandInternal(demand, out exception);

                // We don't record modifiers for the unrestricted permission set in the
                // individual lists.  Therefore, permList.CheckDemandInternal may say
                // that we have to continue the stackwalk, but we know better.

                if (cont && permToken.m_isUnrestricted)
                {
                    if ((m_state & PermissionListSetState.UnrestrictedDeny) != 0)
                    {
                        exception = new SecurityException(String.Format( Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName ) );
                        return false;
                    }
                    else
                    {
                        cont = cont && ((m_state & PermissionListSetState.UnrestrictedAssert) == 0);
                    }
                }

                return cont;
            }
#if _DEBUG
            // Let's check to make sure we always pass demands for empty permissions.

            else if (demand.IsSubsetOf( null ))
            {
                BCLDebug.Assert( false, "We should pick of empty demands before this point" );
                exception = null;
                return true;
            }
#endif
            // If the permission is not unrestricted, the lack of a permission list
            // denotes that no frame on the stack granted this permission, and therefore
            // we pass back the failure condition.

            else if (!permToken.m_isUnrestricted)
            {
                exception = new SecurityException(String.Format( Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName ) );
                return false;
            }

            // If this permission list set is not unrestricted and there is no unrestricted assert
            // then the lack of a permission list denotes that no frame on the stack granted
            // this permission, and therefore we pass back the failure condition.  If there is
            // an unrestricted assert, then we pass back success and terminate the stack walk.

            else if (!this.IsUnrestricted())
            {
                exception = new SecurityException(String.Format( Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName ) );
                return false;
            }
            
            // If we made it all the way through, that means that we are in the unrestricted
            // state and that this permission is encompassed in that.  If we have an unrestricted
            // assert, we are done with the state walk (return false), otherwise keep going.

            exception = null;
            return (m_state & PermissionListSetState.UnrestrictedAssert) == 0;
        }
예제 #32
0
        public bool CheckSetDemandInternal(PermissionSet permSet, out Exception exception, bool bNeedAlteredSet, out PermissionSet alteredSet)
        {
            alteredSet = null;

            BCLDebug.Assert(permSet != null, "permSet != null");
            
            // If the compressed stack is not unrestricted and the demand is
            // then we just throw an exception.
            if (!this.m_unrestricted && permSet.IsUnrestricted())
            {
                exception = new SecurityException(Environment.GetResourceString("Security_GenericNoType") );
                return false;
            }
            
            
            TokenBasedSet normalAlteredSet = null;
            TokenBasedSet unrestrictedAlteredSet = null;

            // Check the "normal" permissions since we always know we have to check them.

            bool normalContinue = CheckTokenBasedSets( this.m_normalPermSet, permSet.m_normalPermSet, false, PermissionListSetState.None, out exception, bNeedAlteredSet, out normalAlteredSet );

            if (exception != null)
            {
                return false;
            }
            
            bool unrestrictedContinue = CheckTokenBasedSets( this.m_unrestrictedPermSet, permSet.m_unrestrictedPermSet, m_unrestricted, m_state, out exception, bNeedAlteredSet, out unrestrictedAlteredSet );

            if (exception != null)
            {
                return false;
            }

            if ((m_state & PermissionListSetState.UnrestrictedAssert) != 0)
            {
                // If we are unrestricted, we want to terminate the stack walk based
                // on us having an unrestricted assert.

                if (bNeedAlteredSet)
                    unrestrictedAlteredSet = new TokenBasedSet( 1, 4 );
                unrestrictedContinue = false;
            }

            if (normalContinue || unrestrictedContinue)
            {
                if (!bNeedAlteredSet)
                    return true;

                // If we need to continue, let's build the altered set.  We only
                // need to do this if 1) our original demand is not unrestricted
                // and 2) if we have altered token based sets.

                if (!permSet.IsUnrestricted())
                {
                    if (normalAlteredSet != null || unrestrictedAlteredSet != null)
                    {
                        alteredSet = new PermissionSet( false );

                        if (normalAlteredSet != null)
                            alteredSet.m_normalPermSet = normalAlteredSet;
                        else
                            alteredSet.m_normalPermSet = CopyTokenBasedSet( permSet.m_normalPermSet );

                        if (unrestrictedAlteredSet != null)
                            alteredSet.m_unrestrictedPermSet = unrestrictedAlteredSet;
                        else
                            alteredSet.m_unrestrictedPermSet = CopyTokenBasedSet( permSet.m_unrestrictedPermSet );

                        if (alteredSet.IsEmpty())
                            return false;
                    }
                }

                return true;
            }
            else
            {
                return false;
            }
        }
예제 #33
0
		private void OpenWriteAsyncResponseCallback (IAsyncResult result)
		{
			Exception ex = null;
			try {
				WebResponse response = request.EndGetResponse (result);
				ProcessResponse (response);
			}
			catch (SecurityException se) {
				// SecurityException inside a SecurityException (not a WebException) for SL compatibility
				ex = new SecurityException (String.Empty, se);
			}
			catch (Exception e) {
				ex = new WebException ("Could not complete operation.", e, WebExceptionStatus.UnknownError, null);
			}
			finally {
				callback_data.sync_context.Post (delegate (object sender) {
					OnWriteStreamClosed (new WriteStreamClosedEventArgs (ex));
				}, null);
			}
		}
예제 #34
0
        internal bool CheckDemandInternal(CodeAccessPermission demand, out Exception exception)
        {
            BCLDebug.Assert(m_head != null, "m_head != null");
            for (PListNode pnext = m_head; pnext != null; pnext = pnext.next)
            {
                if (pnext.perm == null)
                {
                    // If this is a grant set or a permit only, then we should fail since null indicates the empty permission.
                    if (pnext.type == MatchChecked || pnext.type == MatchPermitOnly)
                    {
                        BCLDebug.Assert(!demand.IsSubsetOf(null), "By the time we get here, demands that are subsets of null should have been terminated");
                        exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName));
                        return(false);
                    }

                    // If this is a deny, then we should fail since null indicates the unrestricted permission.
                    if (pnext.type == MatchDeny)
                    {
                        exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName));
                        return(false);
                    }

                    // If this is an assert, then we should return success and terminate the stack walk since
                    // null indicates the unrestricted permission.
                    if (pnext.type == MatchAssert)
                    {
                        exception = null;
                        return(false);
                    }

                    // If this is anything else, then we should act confused.
                    // This case is unexpected.
                    BCLDebug.Assert(false, "This case should never happen");
                    exception = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidState"));
                    return(false);
                }

                CodeAccessPermission cap = pnext.perm;
                switch (pnext.type)
                {
                case MatchChecked:
                case MatchPermitOnly:
                    if (!demand.IsSubsetOf(cap))
                    {
                        exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName));
                        return(false);
                    }
                    break;

                case MatchAssert:
                    if (demand.IsSubsetOf(cap))
                    {
                        exception = null;
                        return(false);
                    }
                    break;

                case MatchDeny:
                    if (demand.Intersect(cap) != null)
                    {
                        exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName));
                        return(false);
                    }
                    break;

                default:
                    // Illegal entry
                    exception = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidState"));
                    return(false);
                }
            }

            exception = null;
            return(true);
        }
예제 #35
0
        private bool CheckFault(DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                return true;
            }

            if (e.Error == null)
            {
                return false;
            }

            Exception error = e.Error;
            if (e.Error is SecurityException)
            {
                //TODO:资源
                error = new SecurityException(ExceptionStrings.InvalidURISchemeHost, error);
            }
            this.Error = error;

            return true;
        }
예제 #36
0
        public void RunJob()
        {
            IPrincipal oldPrincipal = null;
            try
            {
                oldPrincipal = Thread.CurrentPrincipal;
            }
            catch
            {
            }
            try
            {
                if (principal != null)
                {
                    Thread.CurrentPrincipal = principal;
                }
                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);
                Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
                FolderDao = Global.DaoFactory.GetFolderDao();
                FileDao = Global.DaoFactory.GetFileDao();
                TagDao = Global.DaoFactory.GetTagDao();
                FilesSecurity = new FileSecurity(Global.DaoFactory);
                Store = Global.GetStore();

                try
                {
                    step = InitProgressStep();
                }
                catch
                {
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, authError);
            }
            catch (Exception error)
            {
                Error = error;
                LogManager.GetLogger("ASC.Files").Error(error);
            }
            finally
            {
                IsCompleted = true;
                Percentage = 100;
                try
                {
                    if (oldPrincipal != null) Thread.CurrentPrincipal = oldPrincipal;
                    FolderDao.Dispose();
                    FileDao.Dispose();
                    TagDao.Dispose();
                }
                catch
                {
                }
            }
        }
 private static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destAssembly, Type resolvedType)
 {
     if ((!FormatterServices.UnsafeTypeForwardersIsEnabled() && (sourceAssembly != destAssembly)) && !destAssembly.PermissionSet.IsSubsetOf(sourceAssembly.PermissionSet))
     {
         TypeInformation typeInformation = BinaryFormatter.GetTypeInformation(resolvedType);
         if (!typeInformation.HasTypeForwardedFrom)
         {
             SecurityException exception2 = new SecurityException {
                 Demanded = sourceAssembly.PermissionSet
             };
             throw exception2;
         }
         Assembly assembly = null;
         try
         {
             assembly = Assembly.Load(typeInformation.AssemblyString);
         }
         catch
         {
         }
         if (assembly != sourceAssembly)
         {
             SecurityException exception = new SecurityException {
                 Demanded = sourceAssembly.PermissionSet
             };
             throw exception;
         }
     }
 }
        private static bool CheckTokenBasedSets(TokenBasedSet thisSet, TokenBasedSet permSet, bool unrestricted, PermissionListSetState state, bool createException, out Exception exception, bool bNeedAlteredSet, out TokenBasedSet alteredSet)
        {
            alteredSet = null;

            // If the set is empty, there is no reason to walk the
            // stack.

            if (permSet == null || permSet.FastIsEmpty())
            {
                if (bNeedAlteredSet)
                {
                    alteredSet = new TokenBasedSet(1, 4);
                }
                exception = null;
                return(false);
            }

            int permMaxIndex = permSet.GetMaxUsedIndex();

            // Make a quick check to see if permSet definitely contains permissions that this set doesn't

            if (permMaxIndex > thisSet.GetMaxUsedIndex())
            {
                // The only way we don't want to throw an exception is
                // if we are unrestricted.  Then, if we don't want to throw
                // an exception we may want to terminate the stack walk
                // based on an unrestricted assert.

                if (unrestricted)
                {
                    if (((state & PermissionListSetState.UnrestrictedAssert) != 0))
                    {
                        if (bNeedAlteredSet)
                        {
                            alteredSet = new TokenBasedSet(1, 4);
                        }
                        exception = null;
                        return(false);
                    }
                    else
                    {
                        exception = null;
                        return(true);
                    }
                }
                else
                {
                    if (createException)
                    {
                        exception = new SecurityException(Environment.GetResourceString("Security_GenericNoType"));
                    }
                    else
                    {
                        exception = GetStaticException();
                    }
                    return(false);
                }
            }


            bool continueStackWalk = false;

            // We know that checking to <permMaxIndex> is sufficient because of above check
            for (int i = 0; i <= permMaxIndex; i++)
            {
                Object obj = permSet.GetItem(i);

                if (obj != null)
                {
                    CodeAccessPermission cap = (CodeAccessPermission)obj;

                    PermissionList permList = (PermissionList)thisSet.GetItem(i);

                    if (permList != null)
                    {
                        bool tempContinue = permList.CheckDemandInternal(cap, createException, out exception);

                        if (exception != null)
                        {
                            return(false);
                        }

                        if (tempContinue)
                        {
                            // If we are supposed to continue the stack walk but there is an unrestricted
                            // deny, then we should fail.

                            if (((state & PermissionListSetState.UnrestrictedDeny) != 0) && (cap is IUnrestrictedPermission))
                            {
                                if (createException)
                                {
                                    exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), cap.GetType().AssemblyQualifiedName));
                                }
                                else
                                {
                                    exception = GetStaticException();
                                }
                                return(false);
                            }

                            continueStackWalk = true;
                        }
                        else if (((state & PermissionListSetState.UnrestrictedAssert) == 0) && (cap is IUnrestrictedPermission))
                        {
                            // We only want to build the altered set if we don't have an
                            // unrestricted assert because we know if we have an unrestricted
                            // assert and we don't throw an exception that the stackwalk should
                            // include no unrestricted permissions.

                            if (bNeedAlteredSet)
                            {
                                if (alteredSet == null)
                                {
                                    alteredSet = CopyTokenBasedSet(permSet);
                                }

                                alteredSet.SetItem(i, null);
                            }
                        }
                    }
                    else
                    {
                        if (!unrestricted)
                        {
                            if (createException)
                            {
                                exception = new SecurityException(String.Format(Environment.GetResourceString("Security_Generic"), cap.GetType().AssemblyQualifiedName));
                            }
                            else
                            {
                                exception = GetStaticException();
                            }
                            return(false);
                        }
                    }
                }
            }

            exception = null;
            return(continueStackWalk);
        }
예제 #39
0
        private static bool CheckTokenBasedSets( TokenBasedSet thisSet, TokenBasedSet permSet, bool unrestricted, PermissionListSetState state, out Exception exception, bool bNeedAlteredSet, out TokenBasedSet alteredSet )
        {
            alteredSet = null;

            // If the set is empty, there is no reason to walk the
            // stack.

            if (permSet == null || permSet.IsEmpty())
            {
                if (bNeedAlteredSet)
                    alteredSet = new TokenBasedSet( 1, 4 );
                exception = null;
                return false;
            }

            int permMaxIndex = permSet.GetMaxUsedIndex();
            
            // Make a quick check to see if permSet definitely contains permissions that this set doesn't
            
            if (permMaxIndex > thisSet.GetMaxUsedIndex())
            {
                // The only way we don't want to throw an exception is
                // if we are unrestricted.  Then, if we don't want to throw
                // an exception we may want to terminate the stack walk
                // based on an unrestricted assert.

                if (unrestricted)
                {
                    if (((state & PermissionListSetState.UnrestrictedAssert) != 0))
                    {
                        if (bNeedAlteredSet)
                            alteredSet = new TokenBasedSet( 1, 4 );
                        exception = null;
                        return false;
                    }
                    else
                    {
                        exception = null;
                        return true;
                    }
                }
                else
                {
                    exception = new SecurityException(Environment.GetResourceString("Security_GenericNoType") );
                    return false;
                }
            }


            bool continueStackWalk = false;
            
            // We know that checking to <permMaxIndex> is sufficient because of above check
            for (int i = 0; i <= permMaxIndex; i++)
            {
                Object obj = permSet.GetItem(i);
                
                if (obj != null)
                {
                    CodeAccessPermission cap = (CodeAccessPermission)obj;

                    PermissionList permList = (PermissionList)thisSet.GetItem(i);
                    
                    if (permList != null)
                    {
                        bool tempContinue = permList.CheckDemandInternal(cap, out exception);

                        if (exception != null)
                            return false;

                        if (tempContinue)
                        {
                            // If we are supposed to continue the stack walk but there is an unrestricted
                            // deny, then we should fail.

                            if (((state & PermissionListSetState.UnrestrictedDeny) != 0) && (cap is IUnrestrictedPermission))
                            {
                                exception = new SecurityException(String.Format( Environment.GetResourceString("Security_Generic"), cap.GetType().AssemblyQualifiedName ) );
                                return false;
                            }

                            continueStackWalk = true;
                        }
                        else if (((state & PermissionListSetState.UnrestrictedAssert) == 0) && (cap is IUnrestrictedPermission))
                        {
                            // We only want to build the altered set if we don't have an
                            // unrestricted assert because we know if we have an unrestricted
                            // assert and we don't throw an exception that the stackwalk should
                            // include no unrestricted permissions.

                            if (bNeedAlteredSet)
                            {
                                if (alteredSet == null)
                                    alteredSet = CopyTokenBasedSet( permSet );

                                alteredSet.SetItem( i, null );
                            }
                        }
                    }
                    else
                    {
                        if (!unrestricted)
                        {
                            exception = new SecurityException(String.Format( Environment.GetResourceString("Security_Generic"), cap.GetType().AssemblyQualifiedName ) );
                            return false;
                        }
                    }
                }
            }

            exception = null;
            return continueStackWalk;
        }
예제 #40
0
        private void OnEnter(Object sender, EventArgs eventArgs)
        {
            HttpApplication application = (HttpApplication)sender;

            if (!application.Context.Request.IsLocal) {
                SecurityException securityException = new SecurityException((string)HttpContext.GetGlobalResourceObject("GlobalResources", "WebAdmin_ConfigurationIsLocalOnly"));
                WebAdminPage.SetCurrentException(application.Context, securityException);
                application.Server.Transfer("~/error.aspx");
            }

            if (application != null) {
                SetSessionVariables(application);
            }
            application.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        }
예제 #41
0
        /// <SecurityNote>
        /// Review - calculates whether this Xml type requires MemberAccessPermission for deserialization.
        ///          since this information is used to determine whether to give the generated code access
        ///          permissions to private members, any changes to the logic should be reviewed.
        /// </SecurityNote>
        private bool RequiresMemberAccessForCreate(SecurityException securityException)
        {
            if (!IsTypeVisible(UnderlyingType))
            {
                if (securityException != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new SecurityException(SR.Format(SR.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)),
                        securityException));
                }
                return true;
            }

            if (ConstructorRequiresMemberAccess(GetConstructor()))
            {
                if (securityException != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new SecurityException(SR.Format(SR.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)),
                        securityException));
                }
                return true;
            }

            return false;
        }
        /// <summary>
        /// Retrieves an <c>Account</c> from the repository using the id of
        /// the account
        /// </summary>
        /// <param name="accountId">The id of the account to retrieve</param>
        /// <param name="identity">The identity whose credentials are used to authenticate
        /// and authorize the action</param>
        /// <returns>The retrieved <c>Account</c> if it is found in the repository
        /// or null if it is not found</returns>
        public AccountModels.Account GetAccountById(int accountId, IIdentity identity)
        {
            logger.EnterMethod("GetAccountById");

            var requestedAccount = accountReadRepository.FindBy(account => account.Id.Equals(accountId));

            var user = Membership.GetUser(identity.Name, false);

            if (user == null || !requestedAccount.UserId.Equals(user.ProviderUserKey))
            {
                var securityException =
                    new SecurityException(
                        string.Format(
                            "The user {0} is not a system administrator and therefore cannot retrieve the list of accounts.",
                            identity.Name));

                logger.LogExceptionWithMessage(securityException, "SecurityException thrown in GetAccountById");

                throw securityException;
            }

            logger.LeaveMethod("GetAccountById");
            return requestedAccount;
        }