Пример #1
0
 private static void PrivilegedStartLogicalOperation()
 {
     _unmanagedCodePermission.Assert();
     try
     {
         Trace.CorrelationManager.StartLogicalOperation();
     }
     finally
     {
         SecurityPermission.RevertAssert();
     }
 }
    public static void Main()
    {
        SecurityPermission perm = new
            SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

           // The method itself is attached with the security permission Deny
           // for unmanaged code, which will override the Assert permission in
           // this stack frame. However, because you are using
           // SuppressUnmanagedCodeSecurityAttribute, you can still call the
           // unmanaged methods successfully.
           // The code should use other security checks to ensure that you
           // don't incur a security hole.
           perm.Assert();
           CallUnmanagedCodeWithoutPermission();

           // The method itself is attached with the security permission
           // Assert for unmanaged code, which will override the Deny
           // permission in this stack frame. Because you are using
           // SuppressUnmanagedCodeSecurityAttribute, you can call the
           // unmanaged methods successfully.
           // The SuppressUnmanagedCodeSecurityAttribute will let you succeed,
           // even if you don't have a permission.
           perm.Deny();
           CallUnmanagedCodeWithPermission();
    }
        private static void SafeSetPrincipal(IPrincipal principal)
        {
            SecurityPermission controlPrincipalPermission = new SecurityPermission(SecurityPermissionFlag.ControlPrincipal);

            controlPrincipalPermission.Assert();
            Thread.CurrentPrincipal = principal;
        }
Пример #4
0
        internal static Win32Exception CreateSafeWin32Exception(int error)
        {
            Win32Exception newException = null;
            // Need to assert SecurtiyPermission, otherwise Win32Exception
            // will not be able to get the error message. At this point the right
            // permissions have already been demanded.
            SecurityPermission securityPermission = new SecurityPermission(PermissionState.Unrestricted);

            securityPermission.Assert();
            try {
                if (error == 0)
                {
                    newException = new Win32Exception();
                }
                else
                {
                    newException = new Win32Exception(error);
                }
            }
            finally {
                SecurityPermission.RevertAssert();
            }

            return(newException);
        }
Пример #5
0
    private static void CallUnmanagedCodeWithPermission()
    {
        // Create a security permission object to describe the
        // UnmanagedCode permission:
        SecurityPermission perm =
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

        // Check that you have permission to access unmanaged code.
        // If you don't have permission to access unmanaged code, then
        // this call will throw a SecurityException.
        // Even though the CallUnmanagedCodeWithPermission method
        // is called from a stack frame that already
        // calls Assert for unmanaged code, you still cannot call native
        // code. Because you use Deny here, the permission gets
        // overwritten.
        perm.Assert();

        try
        {
            Console.WriteLine("Attempting to call unmanaged code with permission.");
            NativeMethods.puts("Hello World!");
            NativeMethods._flushall();
            Console.WriteLine("Called unmanaged code with permission.");
        }
        catch (SecurityException)
        {
            Console.WriteLine("Caught Security Exception attempting to call unmanaged code. Whoops!");
        }
    }
    private static void CallUnmanagedCodeWithPermission()
    {
        // Create a security permission object to describe the
        // UnmanagedCode permission:
        SecurityPermission perm =
           new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

        // Check that you have permission to access unmanaged code.
        // If you don't have permission to access unmanaged code, then
        // this call will throw a SecurityException.
        // Even though the CallUnmanagedCodeWithPermission method
        // is called from a stack frame that already
        // calls Assert for unmanaged code, you still cannot call native
        // code. Because you use Deny here, the permission gets
        // overwritten.
        perm.Assert();

        try
        {
            Console.WriteLine("Attempting to call unmanaged code with permission.");
            NativeMethods.puts("Hello World!");
            NativeMethods._flushall();
            Console.WriteLine("Called unmanaged code with permission.");
        }
        catch (SecurityException)
        {
            Console.WriteLine("Caught Security Exception attempting to call unmanaged code. Whoops!");
        }
    }
    public static void Main()
    {
        SecurityPermission perm = new
                                  SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

        // The method itself is attached with the security permission Deny
        // for unmanaged code, which will override the Assert permission in
        // this stack frame. However, because you are using
        // SuppressUnmanagedCodeSecurityAttribute, you can still call the
        // unmanaged methods successfully.
        // The code should use other security checks to ensure that you
        // don't incur a security hole.
        perm.Assert();
        CallUnmanagedCodeWithoutPermission();

        // The method itself is attached with the security permission
        // Assert for unmanaged code, which will override the Deny
        // permission in this stack frame. Because you are using
        // SuppressUnmanagedCodeSecurityAttribute, you can call the
        // unmanaged methods successfully.
        // The SuppressUnmanagedCodeSecurityAttribute will let you succeed,
        // even if you don't have a permission.
        perm.Deny();
        CallUnmanagedCodeWithPermission();
    }
Пример #8
0
        public ImpersonateUser(string userName, string password, string domain)
        {
            SecurityPermission secPerm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            secPerm.Assert();

            IntPtr token   = IntPtr.Zero;
            bool   success = false;
            string error   = "No specific information.";

            try
            {
                if (LogonUser(userName, domain, password, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, ref token))
                {
                    WindowsIdentity tempWindowsIdentity = new WindowsIdentity(token, "NTLM", WindowsAccountType.Normal, true);
                    impersonationContext = tempWindowsIdentity.Impersonate(); // actually impersonate the user
                    if (impersonationContext != null)
                    {
                        success = true;
                    }
                }
            }
            catch (Exception e)
            {
                error = "ERROR: " + e.Message;
            }

            CodeAccessPermission.RevertAssert();

            if (!success)
            {
                this.Dispose();
                throw new Exception("The logon attempt as user " + domain + "\\" + userName + " with password " + password + " failed. " + error);
            }
        }
Пример #9
0
        public void UninstallAssemblyFromConfig([MarshalAs(UnmanagedType.IUnknown)] ref RegistrationConfig regConfig)
        {
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permission.Demand();
            permission.Assert();
            if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
            {
                RegistrationThreadWrapper wrapper = new RegistrationThreadWrapper(this, regConfig);
                Thread thread = new Thread(new ThreadStart(wrapper.UninstallThread));
                thread.Start();
                thread.Join();
                wrapper.PropUninstallResult();
            }
            else
            {
                TransactionOptions transactionOptions = new TransactionOptions {
                    Timeout        = TimeSpan.FromMinutes(0.0),
                    IsolationLevel = IsolationLevel.Serializable
                };
                CatalogSync obSync = new CatalogSync();
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions, EnterpriseServicesInteropOption.Full))
                {
                    new RegistrationDriver().UninstallAssembly(regConfig, obSync);
                    scope.Complete();
                }
                obSync.Wait();
            }
        }
Пример #10
0
        private static Uri GetDeploymentUri()
        {
            Invariant.Assert(ApplicationDeployment.IsNetworkDeployed);
            AppDomain           currentDomain = AppDomain.CurrentDomain;
            ApplicationIdentity ident         = null;
            string codeBase = null;

            SecurityPermission p1 = new SecurityPermission(SecurityPermissionFlag.ControlDomainPolicy);

            p1.Assert();
            try
            {
                ident = currentDomain.ApplicationIdentity; // ControlDomainPolicy
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }

            SecurityPermission p2 = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            p2.Assert();
            try
            {
                codeBase = ident.CodeBase; // Unmanaged Code permission
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }

            return(new Uri(new Uri(codeBase), new Uri(".", UriKind.Relative)));
        }
Пример #11
0
        [System.Security.SecurityCritical]  // auto-generated
        internal virtual String InternalToString()
        {
            try
            {
#pragma warning disable 618
                SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
#pragma warning restore 618
                sp.Assert();
            }
            catch
            {
                //under normal conditions there should be no exceptions
                //however if something wrong happens we still can call the usual ToString
            }

            // Get the current stack trace string.  On CoreCLR we don't bother
            // to try and include file/line-number information because all AppDomains
            // are sandboxed, and so this won't succeed in most (or all) cases.  Therefore the
            // Demand and exception overhead is a waste.
            // We currently have some bugs in watson bucket generation where the SecurityException
            // here causes us to lose saved bucket parameters.  By not even doing the demand
            // we avoid those problems (although there are deep underlying problems that need to
            // be fixed there - relying on this to avoid problems is incomplete and brittle).
            bool fGetFileLineInfo = true;
#if FEATURE_CORECLR
            fGetFileLineInfo = false;
#endif
            return(ToString(fGetFileLineInfo, true));
        }
Пример #12
0
        public Clerk(string compensator, string description, CompensatorOptions flags)
        {
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permission.Demand();
            permission.Assert();
            this.Init(compensator, description, flags);
        }
Пример #13
0
        private static CultureInfo DesializeCulture(string culture)
        {
            SecurityPermission sp = new SecurityPermission(PermissionState.Unrestricted);

            sp.Assert();
            CultureInfo ci = (CultureInfo)StringToObject(culture);

            return(ci);
        }
Пример #14
0
        public ClerkMonitor()
        {
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permission.Demand();
            permission.Assert();
            this._monitor = new CrmMonitor();
            this._version = 0;
        }
Пример #15
0
 internal static void DemandUnmanagedCode()
 {
     if (_unmanagedCodePermission == null)
     {
         _unmanagedCodePermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     }
     _unmanagedCodePermission.Demand();
     _unmanagedCodePermission.Assert();
 }
Пример #16
0
        /// <include file='doc\CRM.uex' path='docs/doc[@for="Clerk.Clerk1"]/*' />
        public Clerk(String compensator, String description, CompensatorOptions flags)
        {
            SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            sp.Demand();
            sp.Assert();

            Init(compensator, description, flags);
        }
        public void UnloadAppDomain()
        {
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.ControlAppDomain);

            permission.Assert();

            AppDomain.Unload(AppDomain.CurrentDomain);
            // thread will be aborted
        }
Пример #18
0
        /// <include file='doc\CRM.uex' path='docs/doc[@for="ClerkMonitor.ClerkMonitor"]/*' />
        public ClerkMonitor()
        {
            SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            sp.Demand();
            sp.Assert();

            _monitor = new CrmMonitor();
            _version = 0;
        }
Пример #19
0
        private static void SafeSetPrincipal(IPrincipal principal)
        {
            // We really need to null out the principal in order to guarentee CRT initialization will work.
            // It seems safe to assert the ControlPrincipal permission here because of the limited scope that
            // this block will operate under, where all it can do is run the SCrypt library.
            var controlPrincipalPermission = new SecurityPermission(SecurityPermissionFlag.ControlPrincipal);

            controlPrincipalPermission.Assert();
            Thread.CurrentPrincipal = principal;
        }
Пример #20
0
        public Clerk(Type compensator, string description, CompensatorOptions flags)
        {
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permission.Demand();
            permission.Assert();
            this.ValidateCompensator(compensator);
            string str = "{" + Marshal.GenerateGuidForType(compensator) + "}";

            this.Init(str, description, flags);
        }
Пример #21
0
        private const int _COMPlusExceptionCode = unchecked ((int)0xe0524f54); // Win32 exception code for COM+ exceptions

        internal virtual String InternalToString()
        {
            try
            {
                SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
                sp.Assert();
            }
            catch (Exception)
            {
            }
            return(ToString());
        }
Пример #22
0
 private Config()
 {
     // SerializationFormatter permission must be asserted for .NET 1.1 but not 2.0 or later.  Asserting it
     // under .NET 4 under medium trust causes a SecurityException, so we have to assert it programmatically
     // not declaratively.
     if (System.Environment.Version.Major < 2)
     {
         SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.SerializationFormatter);
         perm.Assert();
     }
     this.ResourceManager = ResourceManagerSingleton.ResourceManager;
 }
Пример #23
0
        // Methods
        public UnmanagedStorage(string fileName, bool create)
        {
            OLE_MODE           ole_mode1;
            SecurityPermission permission1 = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            if (create)
            {
                ole_mode1 = OLE_MODE.STGM_CREATE | (OLE_MODE.STGM_SHARE_EXCLUSIVE | OLE_MODE.STGM_READWRITE);
                try
                {
                    permission1.Assert();
                    SafeNativeMethods.StgCreateDocfile(fileName, (int)ole_mode1, 0, out this.storage);
                }
                catch
                {
                    throw new Exception("Need to have unmanaged code rights to execute this code.");
                }
                if (this.storage == null)
                {
                    throw new IOException("Can't create file. Is file with the \"" + fileName + "\" name used by another process?");
                }
            }
            else
            {
                ole_mode1 = OLE_MODE.STGM_SHARE_EXCLUSIVE | OLE_MODE.STGM_READWRITE;
                try
                {
                    permission1.Assert();
                    SafeNativeMethods.StgOpenStorage(fileName, null, (int)ole_mode1, IntPtr.Zero, 0, out this.storage);
                }
                catch
                {
                    throw new Exception("Need to have unmanaged code rights to execute this code.");
                }
                if (this.storage == null)
                {
                    throw new IOException("Can't open file. Maybe file with the \"" + fileName + "\" name doesn't exist, is not in application folder or is used by another process? Only XLS files from Excel 97 and on are supported.");
                }
            }
        }
        private static void Initialise()
        {
            if (null == m_Application)
            {
                try
                {
                    SecurityPermission secper = new SecurityPermission(PermissionState.Unrestricted);
                    secper.Assert();
                    object olApplicationInstance = null;
                    try
                    {
                        olApplicationInstance = Marshal.GetActiveObject("Outlook.Application");
                    }
                    catch (COMException comException)
                    {
                        if ((uint)comException.ErrorCode == 0x800401e3)
                        {
                            Console.WriteLine("No running instance of Outlook found.");
                        }
                    }
                    SecurityPermission.RevertAssert();

                    if (null != olApplicationInstance)
                    {
                        if (olApplicationInstance is Outlook.Application)
                        {
                            Console.WriteLine("Binding to existing Outlook instance.");
                            m_Application = olApplicationInstance as Outlook.Application;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Creating a new Outlook instance.");
                        m_Application      = new Outlook.Application();
                        newOutlookInstance = true;
                    }
                    if (null != m_Application)
                    {
                        m_NameSpace = m_Application.GetNamespace("MAPI");
                    }
                    else
                    {
                        Console.WriteLine("ERROR: Unable to start Outlook!");
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Unable to initialise application object. Error: " + exception.ToString());
                }
            }
        }
        internal virtual string InternalToString()
        {
            try
            {
                SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
                securityPermission.Assert();
            }
            catch
            {
            }
            bool needFileLineInfo = true;

            return(this.ToString(needFileLineInfo, true));
        }
Пример #26
0
        /// <include file='doc\CRM.uex' path='docs/doc[@for="Clerk.Clerk"]/*' />
        public Clerk(Type compensator, String description, CompensatorOptions flags)
        {
            SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            sp.Demand();
            sp.Assert();

            Platform.Assert(Platform.W2K, "CRM");
            ValidateCompensator(compensator);

            String progid = "{" + Marshal.GenerateGuidForType(compensator) + "}";

            Init(progid, description, flags);
        }
    public void RunProcess(string FileName, string Arguments)
    {
        SecurityPermission SP = new SecurityPermission(SecurityPermissionFlag.Execution);

        SP.Assert();
        process.StartInfo.UseShellExecute        = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError  = true;
        process.StartInfo.CreateNoWindow         = true;
        process.StartInfo.FileName         = FileName;
        process.StartInfo.Arguments        = Arguments;
        process.StartInfo.WorkingDirectory = "";
        process.OutputDataReceived        += ProcessCompleted;
        process.Start();
    }
Пример #28
0
 void IMdiClientWindow.BorderColorChanged()
 {
     if (IsManagerEnabled)
     {
         SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         try
         {
             securityPermission.Assert();
             NativeWindowMethods.RedrawWindowApi(base.Handle, IntPtr.Zero, IntPtr.Zero, 1089u);
         }
         catch (SecurityException)
         {
         }
     }
 }
Пример #29
0
        private static string GetCurrentOEMCPEncoding(int code)
        {
            SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            sp.Assert();//Blessed Assert
            try
            {
                int cp = UnsafeNativeMethods.GetOEMCP();
                return(CharacterEncoding(cp, code));
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }
        }
    public static void Main()
    {
        // The method itself will call the security permission Deny
        // for unmanaged code, which will override the Assert permission
        // in this stack frame.
        SecurityPermission perm = new
            SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
        perm.Assert();
        CallUnmanagedCodeWithoutPermission();

        // The method itself will call the security permission Assert
        // for unmanaged code, which will override the Deny permission in
        // this stack frame.
        perm.Deny();
        CallUnmanagedCodeWithPermission();
    }
Пример #31
0
    public static void Main()
    {
        SecurityPermission perm = new
                                  SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

        // The method itself is attached with the security permission
        // Deny for unmanaged code, which will override
        // the Assert permission in this stack frame.
        perm.Assert();
        CallUnmanagedCodeWithoutPermission();

        // The method itself is attached with the security permission
        // Assert for unmanaged code, which will override the Deny
        // permission in this stack frame.
        perm.Deny();
        CallUnmanagedCodeWithPermission();
    }
    public static void Main()
    {
        SecurityPermission perm = new
            SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

        // The method itself is attached with the security permission
        // Deny for unmanaged code, which will override
        // the Assert permission in this stack frame.
        perm.Assert();
        CallUnmanagedCodeWithoutPermission();

        // The method itself is attached with the security permission
        // Assert for unmanaged code, which will override the Deny
        // permission in this stack frame.
        perm.Deny();
        CallUnmanagedCodeWithPermission();
    }
Пример #33
0
    public static void Main()
    {
        // The method itself will call the security permission Deny
        // for unmanaged code, which will override the Assert permission
        // in this stack frame.
        SecurityPermission perm = new
                                  SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

        perm.Assert();
        CallUnmanagedCodeWithoutPermission();

        // The method itself will call the security permission Assert
        // for unmanaged code, which will override the Deny permission in
        // this stack frame.
        perm.Deny();
        CallUnmanagedCodeWithPermission();
    }
Пример #34
0
        private object OnUnregisterTextStore(object arg)
        {
            if (this._threadManager == null || this._threadManager.Value == null)
            {
                return(null);
            }
            SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            TextStore          textStore          = (TextStore)arg;

            if (textStore.ThreadFocusCookie != -1)
            {
                UnsafeNativeMethods.ITfSource tfSource = this._threadManager.Value as UnsafeNativeMethods.ITfSource;
                tfSource.UnadviseSink(textStore.ThreadFocusCookie);
                textStore.ThreadFocusCookie = -1;
            }
            UnsafeNativeMethods.ITfContext tfContext;
            textStore.DocumentManager.GetBase(out tfContext);
            if (tfContext != null)
            {
                if (textStore.EditSinkCookie != -1)
                {
                    UnsafeNativeMethods.ITfSource tfSource = tfContext as UnsafeNativeMethods.ITfSource;
                    tfSource.UnadviseSink(textStore.EditSinkCookie);
                    textStore.EditSinkCookie = -1;
                }
                Marshal.ReleaseComObject(tfContext);
            }
            securityPermission.Assert();
            try
            {
                textStore.DocumentManager.Pop(UnsafeNativeMethods.PopFlags.TF_POPF_ALL);
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            Marshal.ReleaseComObject(textStore.DocumentManager);
            textStore.DocumentManager = null;
            this._registeredtextstorecount--;
            if (this._isDispatcherShutdownFinished && this._registeredtextstorecount == 0)
            {
                this.DeactivateThreadManager();
            }
            return(null);
        }