Esempio n. 1
0
        /// <summary>
        /// Creates a new TRACKMOUSEEVENT struct with default settings
        /// </summary>
        public TRACKMOUSEEVENT()
        {
            // Marshal.SizeOf() uses SecurityAction.LinkDemand to prevent
            // it from being called from untrusted code, so make sure we
            // have permission to call it
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permission.Demand();

            this.cbSize = Marshal.SizeOf(typeof(TRACKMOUSEEVENT));

            this.dwFlags     = 0;
            this.hwndTrack   = IntPtr.Zero;
            this.dwHoverTime = 100;
        }
Esempio n. 2
0
        public FormoZ()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;

            try
            {
                SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                sp.Demand();
            }
            catch (Exception ex)
            {
                fConsole.WriteLine("Demand for SecurityPermissionFlag.UnmanagedCode failed: " + ex.Message);
            }
        }
Esempio n. 3
0
 /// <include file='doc\factory.uex' path='docs/doc[@for="ClrObjectFactory.CreateFromAssembly"]/*' />
 public object CreateFromAssembly(string AssemblyName, string TypeName, string Mode)
 {
     try
     {
         SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         sp.Demand();
         // check to ensure this call is not being used to activate private classes in our assembly
         if (AssemblyName.StartsWith("System.EnterpriseServices"))
         {
             return(null);
         }
         string PhysicalPath = Publish.GetClientPhysicalPath(false);
         string cfgName      = PhysicalPath + TypeName + ".config";
         // we only remote activate if there is a configuration file in this case
         {
             if (File.Exists(cfgName))
             {
                 lock (_htTypes)
                     if (!_htTypes.ContainsKey(cfgName))
                     {
                         RemotingConfiguration.Configure(cfgName);
                         _htTypes.Add(cfgName, cfgName);
                     }
             }
             else //COM+ 26264 - no configuration file is an error condition
             {
                 throw new COMException(Resource.FormatString("Err_ClassNotReg"), Util.REGDB_E_CLASSNOTREG);
             }
         }
         Assembly objAssem = Assembly.LoadWithPartialName(AssemblyName);
         if (null == objAssem)
         {
             throw new COMException(Resource.FormatString("Err_ClassNotReg"), Util.REGDB_E_CLASSNOTREG);
         }
         Object o = objAssem.CreateInstance(TypeName);
         if (null == o)
         {
             throw new COMException(Resource.FormatString("Err_ClassNotReg"), Util.REGDB_E_CLASSNOTREG);
         }
         return(o);
     }
     catch (Exception e)
     {
         ComSoapPublishError.Report(e.ToString());
         throw;
     }
 }
        public static bool DeleteCredentials(string target)
        {
#if NET45
            try
            {
                var permissions = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                permissions.Demand();

                return(CredDelete(target, 1, 0));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
#endif
            return(false);
        }
        internal static void DemandClientSecurityPermissions <T>(ClientBase <T> proxy) where T : class
        {
            SecurityPermissionFlag flags = SecurityPermissionFlag.Execution;

            PermissionSet securitySet = new PermissionSet(PermissionState.None);

            if (proxy.Endpoint.Binding is NetNamedPipeBinding)
            {
                NetNamedPipeBinding ipcBinding = proxy.Endpoint.Binding as NetNamedPipeBinding;
                if (ipcBinding.Security.Mode == NetNamedPipeSecurityMode.Transport)
                {
                    flags |= SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy;
                }
            }
            //Non-default Windows creds
            if (proxy.ClientCredentials.Windows.ClientCredential.UserName != String.Empty || proxy.ClientCredentials.UserName.UserName != null)
            {
                if (WindowsSecurityEnabled(proxy.Endpoint))
                {
                    flags |= SecurityPermissionFlag.ControlPrincipal;
                }
            }
            if (proxy.Endpoint.Binding is NetTcpBinding)
            {
                NetTcpBinding tcpBinding = proxy.Endpoint.Binding as NetTcpBinding;
                if (tcpBinding.ReliableSession.Enabled)
                {
                    flags |= SecurityPermissionFlag.ControlPolicy;
                }
                if (proxy is DuplexClientBase <T> )
                {
                    flags |= SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence;
                }
            }
            if (MessageSecurityEnabled(proxy.Endpoint))
            {
                if (ValidatesCertificates(proxy.Endpoint) == false && ScopesCertificate(proxy.Endpoint) == false && WindowsSecurityEnabled(proxy.Endpoint) == false)
                {
                    flags |= SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence;
                }
            }
            IPermission securityPermission = new SecurityPermission(flags);

            securityPermission.Demand();
        }
Esempio n. 6
0
 /// <include file='doc\SoapServerInfo.uex' path='docs/doc[@for="SoapUtility.Present"]/*' />
 public void Present()
 {
     try
     {
         SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         sp.Demand();
         Platform.Assert(Platform.Whistler, "SoapUtility.Present");
     }
     catch (Exception e)
     {
         if (e.GetType() == typeof(System.Security.SecurityException))
         {
             string Error = Resource.FormatString("Soap_SecurityFailure");
             ComSoapPublishError.Report(Error);
         }
         throw;
     }
 }
Esempio n. 7
0
        public override void RemoveEventHandler(object target, Delegate handler)
        {
            if (Marshal.IsComObject(target))
            {
                // retrieve sourceIid and dispid
                Guid sourceIid;
                int dispid;
                GetDataForComInvocation(_innerEventInfo, out sourceIid, out dispid);

                // now validate the caller can call into native and redirect to ComEventHelpers.Combine
                SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                perm.Demand();
                System.Runtime.InteropServices.ComEventsHelper.Remove(target, sourceIid, dispid, handler);
            }
            else
            {
                // we are dealing with a managed object - just add the delegate through relection
                _innerEventInfo.RemoveEventHandler(target, handler);
            }
        }
Esempio n. 8
0
        public AssaultHack()
        {
            _showNames         = Settings.Default.ShowNick;
            _showHealth        = Settings.Default.ShowHealth;
            _showNamesAsString = Settings.Default.ShowHealthAsString;
            InitializeComponent();

            //Get permission for working with UnmanagedCode
            //msdn.microsoft.com/en-us/library/xc5yzfbx(v=vs.110)
            //msdn.microsoft.com/en-us/library/ff648663.aspx#c08618429_020
            try
            {
                SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                sp.Demand();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Demand for SecurityPermissionFlag.UnmanagedCode failed: " + ex.Message);
            }
        }
Esempio n. 9
0
        public override void RemoveEventHandler(object target, Delegate handler)
        {
            if (Marshal.IsComObject(target))
            {
                // retrieve sourceIid and dispid
                Guid sourceIid;
                int  dispid;
                GetDataForComInvocation(_innerEventInfo, out sourceIid, out dispid);

                // now validate the caller can call into native and redirect to ComEventHelpers.Combine
                SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                perm.Demand();
                System.Runtime.InteropServices.ComEventsHelper.Remove(target, sourceIid, dispid, handler);
            }
            else
            {
                // we are dealing with a managed object - just add the delegate through relection
                _innerEventInfo.RemoveEventHandler(target, handler);
            }
        }
Esempio n. 10
0
        // Assert the permissions in this set.
        public virtual void Assert()
        {
            // We must have the "Assertion" security flag for this to work.
            SecurityPermission perm;

            perm = new SecurityPermission(SecurityPermissionFlag.Assertion);
            perm.Demand();

            // Assert all of the CodeAccessPermission objects in the set.
            int posn;
            CodeAccessPermission caperm;

            for (posn = 0; posn < permissions.Count; ++posn)
            {
                caperm = (permissions[posn] as CodeAccessPermission);
                if (caperm != null)
                {
                    caperm.Assert(2);
                }
            }
        }
Esempio n. 11
0
        public void SaveIntoMetafile(Stream imageStream, EmfType emfType)
        {
            Bitmap             bitmap             = new Bitmap(base.Width, base.Height);
            Graphics           graphics           = Graphics.FromImage(bitmap);
            SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            securityPermission.Demand();
            IntPtr   hdc       = graphics.GetHdc();
            Metafile metafile  = new Metafile(imageStream, hdc, new Rectangle(0, 0, base.Width, base.Height), MetafileFrameUnit.Pixel, emfType);
            Graphics graphics2 = Graphics.FromImage(metafile);

            if (base.BorderSkinAttributes.SkinStyle != 0)
            {
                graphics2.Clip = new Region(new Rectangle(0, 0, base.Width, base.Height));
            }
            base.chartGraph.IsMetafile = true;
            base.Paint(graphics2, false);
            base.chartGraph.IsMetafile = false;
            byte[] data = new byte[12]
            {
                68,
                117,
                110,
                100,
                97,
                115,
                32,
                67,
                104,
                97,
                114,
                116
            };
            graphics2.AddMetafileComment(data);
            graphics2.Dispose();
            metafile.Dispose();
            graphics.ReleaseHdc(hdc);
            graphics.Dispose();
            bitmap.Dispose();
        }
Esempio n. 12
0
        /// <include file='doc\RegistrationWrappers.uex' path='docs/doc[@for="RegistrationHelper.InstallAssemblyFromConfig"]/*' />
        public void InstallAssemblyFromConfig([MarshalAs(UnmanagedType.IUnknown)] ref RegistrationConfig regConfig)
        {
            // Create a permission object for unmanaged code
            SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            // demand that the caller have this permission
            sp.Demand();

            // now that the caller is clean, assert it from now on.
            sp.Assert();

            Platform.Assert(Platform.W2K, "RegistrationHelper.InstallAssemblyFromConfig");

            if (Thread.CurrentThread.ApartmentState == ApartmentState.STA)
            {
                // HACK:  In order to reduce deadlock likelihood, we need to get off
                // the current STA (into an MTA) in order to do this work.
                // Whip off a new thread...
                RegistrationThreadWrapper wrap = new RegistrationThreadWrapper(this, regConfig);
                Thread t = new Thread(new ThreadStart(wrap.InstallThread));
                t.Start();
                t.Join();
                wrap.PropInstallResult();
            }
            else
            {
                // First, try to do this in a "transacted" manner.  This will
                // return false if we couldn't start up the transaction,
                // true if it succeeded.
                // We only do the transacted install if we're on win2k or higher,
                // cause MTS is all in the registry.
                if (Platform.IsLessThan(Platform.W2K) || !TryTransactedInstall(regConfig))
                {
                    // We need to try a non-transacted install:
                    DBG.Info(DBG.Registration, "Failed to do a transacted install.  Using non-tx install.");
                    RegistrationDriver helper = new RegistrationDriver();
                    helper.InstallAssembly(regConfig, null);
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Gets IOutArchive interface to pack 7-zip archives.
        /// </summary>
        /// <param name="format">Archive format.</param>
        /// <param name="user">Archive format user.</param>
        public static IOutArchive OutArchive(OutArchiveFormat format, object user)
        {
            lock (_syncRoot)
            {
                if (_outArchives[user][format] == null)
                {
#if NET45 || NETSTANDARD2_0
                    var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                    sp.Demand();
#endif
                    if (_modulePtr == IntPtr.Zero)
                    {
                        throw new SevenZipLibraryException();
                    }

                    var createObject = (NativeMethods.CreateObjectDelegate)
                                       Marshal.GetDelegateForFunctionPointer(
                        NativeMethods.GetProcAddress(_modulePtr, "CreateObject"),
                        typeof(NativeMethods.CreateObjectDelegate));
                    var interfaceId = typeof(IOutArchive).GUID;


                    try
                    {
                        var classId = Formats.OutFormatGuids[format];
                        createObject(ref classId, ref interfaceId, out var result);

                        InitUserOutFormat(user, format);
                        _outArchives[user][format] = result as IOutArchive;
                    }
                    catch (Exception)
                    {
                        throw new SevenZipLibraryException("Your 7-zip library does not support this archive type.");
                    }
                }

                return(_outArchives[user][format]);
            }
        }
        internal void ConfigureCollection(ICatalogCollection coll, IConfigCallback cb)
        {
            bool flag = false;
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permission.Demand();
            permission.Assert();
            foreach (object obj2 in cb)
            {
                object a = cb.FindObject(coll, obj2);
                cb.ConfigureDefaults(a, obj2);
            }
            SaveChanges(coll);
            flag = false;
            foreach (object obj4 in cb)
            {
                object obj5 = cb.FindObject(coll, obj4);
                if (cb.Configure(obj5, obj4))
                {
                    flag = true;
                }
            }
            SaveChanges(coll);
            flag = false;
            foreach (object obj6 in cb)
            {
                object obj7 = cb.FindObject(coll, obj6);
                if (cb.AfterSaveChanges(obj7, obj6))
                {
                    flag = true;
                }
            }
            if (flag)
            {
                SaveChanges(coll);
            }
            cb.ConfigureSubCollections(coll);
        }
Esempio n. 15
0
 /// <include file='doc\factory.uex' path='docs/doc[@for="ClrObjectFactory.CreateFromWsdl"]/*' />
 public object CreateFromWsdl(string WsdlUrl, string Mode)
 {
     try
     {
         SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         sp.Demand();
         string PhysicalPath = Publish.GetClientPhysicalPath(true);
         string TypeName     = "";
         string EscUrl       = Url2File(WsdlUrl);
         if ((EscUrl.Length + PhysicalPath.Length) > 250)
         {
             EscUrl = EscUrl.Remove(0, (EscUrl.Length + PhysicalPath.Length) - 250);
         }
         string dllName = EscUrl + ".dll";
         if (!File.Exists(PhysicalPath + dllName))
         {
             GenAssemblyFromWsdl gen = new GenAssemblyFromWsdl();
             gen.Run(WsdlUrl, dllName, PhysicalPath);
         }
         Assembly objAssem   = Assembly.LoadFrom(PhysicalPath + dllName);
         Type[]   AssemTypes = objAssem.GetTypes();
         for (long i = 0; i < AssemTypes.GetLength(0); i++)
         {
             if (AssemTypes[i].IsClass)
             {
                 TypeName = AssemTypes[i].ToString();
             }
         }
         Object o = objAssem.CreateInstance(TypeName);
         return(o);
     }
     catch (Exception e)
     {
         ComSoapPublishError.Report(e.ToString());
         throw;
     }
 }
Esempio n. 16
0
 /// <include file='doc\SoapServerInfo.uex' path='docs/doc[@for="SoapUtility.GetServerBinPath"]/*' />
 public void GetServerBinPath(
     string rootWebServer,
     string inBaseUrl,
     string inVirtualRoot,
     out string binPath
     )
 {
     try
     {
         SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         sp.Demand();
         Platform.Assert(Platform.Whistler, "SoapUtility.GetServerBinPath");
         binPath = SoapServerInfo.ServerPhysicalPath(rootWebServer, inBaseUrl, inVirtualRoot, false) + "\\bin\\";
     }
     catch (Exception e)
     {
         if (e.GetType() == typeof(System.Security.SecurityException))
         {
             string Error = Resource.FormatString("Soap_SecurityFailure");
             ComSoapPublishError.Report(Error);
         }
         throw;
     }
 }
Esempio n. 17
0
        public override void Install(IDictionary stateSaver)
        {
            try
            {
                SecurityPermission permission =
                    new SecurityPermission(PermissionState.Unrestricted);
                permission.Demand();
            }
            catch (SecurityException)
            {
                throw new InstallException(
                          "You have insufficient privileges to " +
                          "register a trust relationship. Start Excel " +
                          "and confirm the trust dialog to run the addin.");
            }
            Uri deploymentManifestLocation = null;

            // NodeXLModification
            //
            // "deploymentManifestLocation" parameter name changed to
            // "deploymentLocation" to make it consistent with
            // ClickOnceInstaller.cs.

            if (Uri.TryCreate(Context.Parameters["deploymentLocation"],
                              UriKind.RelativeOrAbsolute, out deploymentManifestLocation) == false)
            {
                throw new InstallException(
                          "The location of the deployment manifest is missing or invalid.");
            }
            AddInSecurityEntry entry = new AddInSecurityEntry(
                deploymentManifestLocation, RSA_PublicKey);

            UserInclusionList.Add(entry);
            stateSaver.Add("entryKey", deploymentManifestLocation);
            base.Install(stateSaver);
        }
        public static bool PutCredentials(string target, string username, string password)
        {
#if NET45
            if (password.Length > 512)
            {
                Debug.WriteLine("Credentials password is too long.");
                return(false);
            }

            try
            {
                var permissions = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                permissions.Demand();

                var passwordBytes = Encoding.Unicode.GetBytes(password);

                var credential = new CREDENTIAL
                {
                    TargetName         = target,
                    UserName           = username,
                    CredentialBlob     = Marshal.StringToCoTaskMemUni(password),
                    CredentialBlobSize = passwordBytes.Length,
                    Comment            = "Keeper Bio login credentials",
                    Type    = 1,
                    Persist = 2
                };

                return(CredWrite(ref credential, 0));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
#endif
            return(false);
        }
        public void UninstallAssembly(RegistrationConfig regConfig, object obSync)
        {
            CatalogSync        sync       = null;
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permission.Demand();
            permission.Assert();
            if (obSync != null)
            {
                if (!(obSync is CatalogSync))
                {
                    throw new ArgumentException(Resource.FormatString("Err_obSync"));
                }
                sync = (CatalogSync)obSync;
            }
            Assembly        asm  = this.NewLoadAssembly(regConfig.AssemblyFile);
            ApplicationSpec spec = new ApplicationSpec(asm, regConfig);

            if (spec.ConfigurableTypes != null)
            {
                this.PrepDriver(ref spec);
                if (spec.ConfigurableTypes != null)
                {
                    ICatalogObject obj2 = this.FindApplication(this._appColl, spec);
                    if (obj2 == null)
                    {
                        throw new RegistrationException(Resource.FormatString("Reg_AppNotFoundErr", spec));
                    }
                    ICatalogCollection collection = (ICatalogCollection)this._appColl.GetCollection(CollectionName.Components, obj2.Key());
                    string[]           arr        = new string[spec.ConfigurableTypes.Length];
                    int index = 0;
                    foreach (Type type in spec.ConfigurableTypes)
                    {
                        arr[index] = Marshal.GenerateGuidForType(type).ToString();
                        index++;
                    }
                    Populate(collection);
                    bool flag   = true;
                    int  lIndex = 0;
                    while (lIndex < collection.Count())
                    {
                        ICatalogObject obj3 = (ICatalogObject)collection.Item(lIndex);
                        string         g    = (string)obj3.Key();
                        g = new Guid(g).ToString();
                        if (this.FindIndexOf(arr, g) != -1)
                        {
                            collection.Remove(lIndex);
                            if (sync != null)
                            {
                                sync.Set();
                            }
                        }
                        else
                        {
                            lIndex++;
                            flag = false;
                        }
                    }
                    SaveChanges(collection);
                    if (flag)
                    {
                        for (int i = 0; i < this._appColl.Count(); i++)
                        {
                            ICatalogObject obj4 = (ICatalogObject)this._appColl.Item(i);
                            if (obj4.Key().Equals(obj2.Key()))
                            {
                                this._appColl.Remove(i);
                                if (sync != null)
                                {
                                    sync.Set();
                                }
                                break;
                            }
                        }
                        SaveChanges(this._appColl);
                    }
                }
                this.UnregisterAssembly(asm, spec);
                this.CleanupDriver();
            }
        }
        public void InstallAssembly(RegistrationConfig regConfig, object obSync)
        {
            Assembly           asm        = null;
            ApplicationSpec    spec       = null;
            CatalogSync        sync       = null;
            bool               flag       = false;
            bool               flag2      = false;
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            try
            {
                permission.Demand();
                permission.Assert();
                ICatalogObject app = null;
                this.PrepArguments(regConfig);
                asm  = this.NewLoadAssembly(regConfig.AssemblyFile);
                spec = new ApplicationSpec(asm, regConfig);
                if (spec.ConfigurableTypes == null)
                {
                    regConfig.Application = null;
                    regConfig.TypeLibrary = null;
                }
                else
                {
                    if (obSync != null)
                    {
                        if (!(obSync is CatalogSync))
                        {
                            throw new ArgumentException(Resource.FormatString("Err_obSync"));
                        }
                        sync = (CatalogSync)obSync;
                    }
                    this.PrepDriver(ref spec);
                    string message = string.Empty;
                    if (!this.ValidateBitness(spec, out message))
                    {
                        throw new RegistrationException(message);
                    }
                    if ((regConfig.InstallationFlags & InstallationFlags.Register) != InstallationFlags.Default)
                    {
                        flag = !this.IsAssemblyRegistered(spec);
                        this.ClassicRegistration(spec.Assembly);
                        if ((regConfig.InstallationFlags & InstallationFlags.ExpectExistingTypeLib) != InstallationFlags.Default)
                        {
                            RegisterTypeLibrary(spec.TypeLib);
                        }
                        else
                        {
                            flag2 = true;
                            GenerateTypeLibrary(spec.Assembly, spec.TypeLib, new Report(this.ReportWarning));
                        }
                    }
                    if (((regConfig.InstallationFlags & InstallationFlags.Install) != InstallationFlags.Default) && (spec.ConfigurableTypes != null))
                    {
                        if ((regConfig.InstallationFlags & InstallationFlags.CreateTargetApplication) != InstallationFlags.Default)
                        {
                            app = this.CreateApplication(spec, true);
                        }
                        else if ((regConfig.InstallationFlags & InstallationFlags.FindOrCreateTargetApplication) != InstallationFlags.Default)
                        {
                            app = this.FindOrCreateApplication(spec, (regConfig.InstallationFlags & InstallationFlags.ReconfigureExistingApplication) != InstallationFlags.Default);
                        }
                        this.InstallTypeLibrary(spec);
                        if (sync != null)
                        {
                            sync.Set();
                        }
                    }
                    if (((regConfig.InstallationFlags & InstallationFlags.Configure) != InstallationFlags.Default) && (spec.ConfigurableTypes != null))
                    {
                        this.ConfigureComponents(spec);
                        if (sync != null)
                        {
                            sync.Set();
                        }
                    }
                    if (app != null)
                    {
                        this.PostProcessApplication(app, spec);
                    }
                    this.CleanupDriver();
                }
            }
            catch (Exception exception)
            {
                if ((exception is NullReferenceException) || (exception is SEHException))
                {
                    throw;
                }
                if (((exception is SecurityException) || (exception is UnauthorizedAccessException)) || ((exception.InnerException != null) && ((exception.InnerException is SecurityException) || (exception.InnerException is UnauthorizedAccessException))))
                {
                    exception = new RegistrationException(Resource.FormatString("Reg_Unauthorized"), exception);
                }
                if (flag && (null != asm))
                {
                    try
                    {
                        this.ClassicUnregistration(asm);
                    }
                    catch (Exception exception2)
                    {
                        if ((exception2 is NullReferenceException) || (exception2 is SEHException))
                        {
                            throw;
                        }
                    }
                }
                if (flag2 && (null != asm))
                {
                    try
                    {
                        this.UnregisterTypeLib(asm);
                    }
                    catch (Exception exception3)
                    {
                        if ((exception3 is NullReferenceException) || (exception3 is SEHException))
                        {
                            throw;
                        }
                    }
                }
                throw exception;
            }
        }
Esempio n. 21
0
        private IEnumerable <Output> DoInject(
            string assemblyFile,
            string typeName,
            string methodName,
            string strongNameKeyPair,
            string[] assemblySearchDirs)
        {
            OutputCollection outputCollection = new OutputCollection();

            try
            {
                if (String.IsNullOrWhiteSpace(assemblyFile))
                {
                    outputCollection.Add(OutputImportance.Error, "Must specify a valid assembly.");
                    return(outputCollection);
                }

                if (String.IsNullOrWhiteSpace(typeName))
                {
                    typeName = "ModuleInitializer";
                }
                if (String.IsNullOrWhiteSpace(methodName))
                {
                    methodName = "Initialize";
                }

                StrongNameKeyPair snkpair;
                if (!String.IsNullOrWhiteSpace(strongNameKeyPair))
                {
                    if (!File.Exists(strongNameKeyPair))
                    {
                        outputCollection.Add(
                            OutputImportance.Error,
                            "The '{0}' strong name keypair was not found.",
                            strongNameKeyPair);
                        return(outputCollection);
                    }

                    // Accessing public key requires UnmanagedCode security permission.
                    try
                    {
                        SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                        sp.Demand();
                    }
                    catch (Exception e)
                    {
                        outputCollection.Add(
                            OutputImportance.Error,
                            "Could not instrument '{0}' as cannot resign assembly, UnmanagedCode security permission denied.",
                            strongNameKeyPair,
                            e.Message);
                        return(outputCollection);
                    }

                    try
                    {
                        /*
                         * Turns out that if we get the strong name key pair directly using the StrongNameKeyPair(string filename)
                         * constructor overload, then retrieving the public key fails due to file permissions.
                         * Opening the filestream ourselves with read access, and reading the snk that way works, and allows
                         * us to successfully resign (who knew?).
                         */
                        using (FileStream fs = new FileStream(strongNameKeyPair, FileMode.Open, FileAccess.Read))
                            snkpair = new StrongNameKeyPair(fs);

                        // Ensure we can access public key - this will be done by mono later so check works now.
                        // ReSharper disable once UnusedVariable
                        byte[] publicKey = snkpair.PublicKey;
                    }
                    catch (Exception e)
                    {
                        outputCollection.Add(
                            OutputImportance.Error,
                            "Error occurred whilst accessing public key from '{0}' strong name keypair. {1}",
                            strongNameKeyPair,
                            e.Message);
                        return(outputCollection);
                    }
                }
                else
                {
                    // No resigning necessary.
                    snkpair = null;
                }

                if (!File.Exists(assemblyFile))
                {
                    outputCollection.Add(OutputImportance.Error, "The '{0}' assembly was not found.", assemblyFile);
                    return(outputCollection);
                }

                // Look for PDB file.
                string pdbFile = Path.ChangeExtension(assemblyFile, ".pdb");

                // Create resolver for assemblies
                DefaultAssemblyResolver asmResolver = new DefaultAssemblyResolver();

                // Add the search directories to the resolver
                string assemblyDir = Path.GetDirectoryName(Path.GetFullPath(assemblyFile));
                asmResolver.AddSearchDirectory(Path.GetFullPath(assemblyDir));
                foreach (string dir in assemblySearchDirs.Select(Path.GetFullPath).Distinct())
                {
                    if (!string.Equals(dir, assemblyDir))
                    {
                        asmResolver.AddSearchDirectory(dir);
                    }
                }

                // Read the assembly definition
                ReaderParameters readParams = new ReaderParameters(ReadingMode.Immediate);
                readParams.AssemblyResolver = asmResolver;
                bool hasPdb = false;
                if (File.Exists(pdbFile))
                {
                    readParams.ReadSymbols          = true;
                    readParams.SymbolReaderProvider = new PdbReaderProvider();
                    hasPdb = true;
                }
                AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyFile, readParams);
                if (assembly == null)
                {
                    outputCollection.Add(
                        OutputImportance.Error,
                        "Failed to load assembly definition for '{0}'.",
                        assemblyFile);
                    return(outputCollection);
                }

                // Find the main module.
                ModuleDefinition module = assembly.MainModule;
                if (module == null)
                {
                    outputCollection.Add(
                        OutputImportance.Error,
                        "Failed to load main module definition from assembly '{0}'.",
                        assemblyFile);
                    return(outputCollection);
                }

                if (module.Types == null)
                {
                    outputCollection.Add(
                        OutputImportance.Error,
                        "Failed to load main module types from assembly '{0}'.",
                        assemblyFile);
                    return(outputCollection);
                }

                // Find the <Module> type definition
                // ReSharper disable once PossibleNullReferenceException
                TypeDefinition moduleType = module.Types.SingleOrDefault(t => t.Name == "<Module>");
                if (moduleType == null)
                {
                    outputCollection.Add(
                        OutputImportance.Error,
                        "Could not find type '<Module>' in assembly '{0}'.",
                        assemblyFile);
                    return(outputCollection);
                }

                // Find void type
                // ReSharper disable once PossibleNullReferenceException
                TypeReference voidRef = module.TypeSystem.Void;
                if (voidRef == null)
                {
                    outputCollection.Add(
                        OutputImportance.Error,
                        "Could not find type 'void' in assembly '{0}'.",
                        assemblyFile);
                    return(outputCollection);
                }

                // Find the type definition
                // ReSharper disable once PossibleNullReferenceException
                TypeDefinition typeDefinition = module.Types.SingleOrDefault(t => t.Name == typeName);

                if (typeDefinition == null)
                {
                    outputCollection.Add(
                        OutputImportance.Warning,
                        "Could not find type '{0}' in assembly '{1}'.",
                        typeName,
                        assemblyFile);
                    return(outputCollection);
                }

                // Find the method
                MethodDefinition callee = typeDefinition.Methods != null
                    ? typeDefinition.Methods.FirstOrDefault(
                    // ReSharper disable PossibleNullReferenceException
                    m => m.Name == methodName && m.Parameters.Count == 0)
                                          // ReSharper restore PossibleNullReferenceException
                    : null;

                if (callee == null)
                {
                    outputCollection.Add(
                        OutputImportance.Warning,
                        "Could not find method '{0}' with no parameters in type '{1}' in assembly '{2}'.",
                        methodName,
                        typeName,
                        assemblyFile);
                    return(outputCollection);
                }

                if (callee.IsPrivate)
                {
                    outputCollection.Add(
                        OutputImportance.Error,
                        "Method '{0}' in type '{1}' in assembly '{2}' cannot be private as it can't be accessed by the Module Initializer.",
                        methodName,
                        typeName,
                        assemblyFile);
                    return(outputCollection);
                }

                if (!callee.IsStatic)
                {
                    outputCollection.Add(
                        OutputImportance.Error,
                        "Method '{0}' in type '{1}' in assembly '{2}' cannot be an instance method as it can't be instantiated by the Module Initializer.",
                        methodName,
                        typeName,
                        assemblyFile);
                    return(outputCollection);
                }


                outputCollection.Add(
                    OutputImportance.MessageHigh,
                    "Method '{0}' in type '{1}' in assembly '{2}' will be called during Module initialization.",
                    methodName,
                    typeName,
                    assemblyFile);

                // Create the module initializer.
                MethodDefinition cctor = new MethodDefinition(
                    ".cctor",
                    MethodAttributes.Static
                    | MethodAttributes.SpecialName
                    | MethodAttributes.RTSpecialName,
                    voidRef);
                // ReSharper disable PossibleNullReferenceException
                ILProcessor il = cctor.Body.GetILProcessor();
                il.Append(il.Create(OpCodes.Call, callee));
                il.Append(il.Create(OpCodes.Ret));
                moduleType.Methods.Add(cctor);
                // ReSharper restore PossibleNullReferenceException

                WriterParameters writeParams = new WriterParameters();
                if (hasPdb)
                {
                    writeParams.WriteSymbols         = true;
                    writeParams.SymbolWriterProvider = new PdbWriterProvider();
                }
                if (snkpair != null)
                {
                    writeParams.StrongNameKeyPair = snkpair;
                    outputCollection.Add(
                        OutputImportance.MessageHigh,
                        "Assembly '{0}' is being resigned by '{1}'.",
                        assemblyFile,
                        strongNameKeyPair);
                }
                else
                {
                    outputCollection.Add(
                        OutputImportance.MessageHigh,
                        "Assembly '{0}' will not be resigned.",
                        assemblyFile);
                }

                assembly.Write(assemblyFile, writeParams);
                return(outputCollection);
            }
            catch (Exception ex)
            {
                outputCollection.Add(OutputImportance.Error, "An unexpected error occurred. {0}", ex.Message);
                return(outputCollection);
            }
        }
Esempio n. 22
0
 static void DemandException(SecurityPermission denyPermission)
 {
     denyPermission.Demand();
 }
Esempio n. 23
0
        static void Main()
        {
            // Check security
            try
            {
                SecurityPermission permissions = new SecurityPermission(PermissionState.Unrestricted);
                permissions.Demand();
            }
            catch (SecurityException)
            {
                MessageBox.Show(
                    "Vha.Chat was unable to obtain the required execution permissions.\n" +
                    "This might be because you're attempting to run this application from a network drive or due to specific restrictions setup on your machine.\n\n" +
                    "This application will now close.",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Initialize Windows.Forms application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException);
#endif

            // Fix working directory
            string path = Assembly.GetExecutingAssembly().Location;
            if (path.LastIndexOf(Path.DirectorySeparatorChar) > 0)
            {
                path = Path.GetDirectoryName(path);
                Environment.CurrentDirectory = path;
            }

            // Load initial configuration
            Data.Base data = Data.Base.Load("Configuration.xml");
            if (data == null)
            {
                data = new Data.ConfigurationV1();
            }
            while (data.CanUpgrade)
            {
                data = data.Upgrade();
            }
            if (data.Type != typeof(ConfigurationV1))
            {
                throw new ArgumentException("Unexpected data type in Configuration.xml: " + data.Type.ToString());
            }
            ConfigurationV1 configData = (ConfigurationV1)data;

            // Detect folders
            string defaultPath          = Path.GetFullPath(configData.OptionsPath);
            bool   defaultOptionsExists = File.Exists(defaultPath + Path.DirectorySeparatorChar + configData.OptionsFile);
            string appDataPath          = string.Format("{1}{0}{2}",
                                                        Path.DirectorySeparatorChar, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Vha.Chat");
            bool appDataOptionsExists = File.Exists(appDataPath + Path.DirectorySeparatorChar + configData.OptionsFile);

            // Determine default folder
            if (defaultOptionsExists)
            {
                configData.OptionsPath = defaultPath;
            }
            else if (appDataOptionsExists)
            {
                configData.OptionsPath = appDataPath;
            }
            else
            {
                // Show directory selection form
                DirectorySelectionForm form = new DirectorySelectionForm(
                    configData, defaultPath, appDataPath);
                Application.Run(form);
                // Guess the user didn't like Vha.Chat :(
                if (form.DialogResult != DialogResult.OK)
                {
                    return;
                }
            }

            // Create context
            Configuration configuration = new Configuration(configData);
            Context       context       = new Context(configuration);
            context.Options.Save();
#if !DEBUG
            context.ExceptionEvent += new Handler <Exception>(UnhandledException);
#endif

            // Store config directory
            ApplicationConfigDirectory = configData.OptionsPath;

            // Start application
            ApplicationContext          = new ApplicationContext();
            ApplicationContext.MainForm = new AuthenticationForm(context);
            Application.Run(ApplicationContext);
        }
        internal static void DemandAsyncPermissions()
        {
            IPermission permission = new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);

            permission.Demand();
        }
Esempio n. 25
0
        /// <summary>
        /// Set the intrinsic properties such as MachineName and UserIdentity.
        /// </summary>
        private void CollectIntrinsicProperties()
        {
            this.TimeStamp = DateTime.UtcNow;

            if (Tracer.IsTracingAvailable())
            {
                try
                {
                    this.ActivityId = GetActivityId();
                }
                catch (Exception)
                {
                    this.ActivityId = Guid.Empty;
                }
            }
            else
            {
                this.ActivityId = Guid.Empty;
            }

            // do not try to avoid the security exception, as it would only duplicate the stack walk
            try
            {
                MachineName = Environment.MachineName;
            }
            catch (Exception e)
            {
                this.MachineName = String.Format(Properties.Resources.Culture, Properties.Resources.IntrinsicPropertyError, e.Message);
            }

            try
            {
                appDomainName = AppDomain.CurrentDomain.FriendlyName;
            }
            catch (Exception e)
            {
                appDomainName = String.Format(Properties.Resources.Culture, Properties.Resources.IntrinsicPropertyError, e.Message);
            }

            // check whether the unmanaged code permission is available to avoid three potential stack walks
            bool unmanagedCodePermissionAvailable      = false;
            SecurityPermission unmanagedCodePermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            // avoid a stack walk by checking for the permission on the current assembly. this is safe because there are no
            // stack walk modifiers before the call.
            if (SecurityManager.IsGranted(unmanagedCodePermission))
            {
                try
                {
                    unmanagedCodePermission.Demand();
                    unmanagedCodePermissionAvailable = true;
                }
                catch (SecurityException)
                { }
            }

            if (unmanagedCodePermissionAvailable)
            {
                try
                {
                    processId = GetCurrentProcessId();
                }
                catch (Exception e)
                {
                    processId = String.Format(Properties.Resources.Culture, Properties.Resources.IntrinsicPropertyError, e.Message);
                }

                try
                {
                    processName = GetProcessName();
                }
                catch (Exception e)
                {
                    processName = String.Format(Properties.Resources.Culture, Properties.Resources.IntrinsicPropertyError, e.Message);
                }

                try
                {
                    win32ThreadId = GetCurrentThreadId();
                }
                catch (Exception e)
                {
                    win32ThreadId = String.Format(Properties.Resources.Culture, Properties.Resources.IntrinsicPropertyError, e.Message);
                }
            }
            else
            {
                processId = String.Format(Properties.Resources.Culture,
                                          Properties.Resources.IntrinsicPropertyError,
                                          Properties.Resources.LogEntryIntrinsicPropertyNoUnmanagedCodePermissionError);
                processName = String.Format(Properties.Resources.Culture,
                                            Properties.Resources.IntrinsicPropertyError,
                                            Properties.Resources.LogEntryIntrinsicPropertyNoUnmanagedCodePermissionError);
                win32ThreadId = String.Format(Properties.Resources.Culture,
                                              Properties.Resources.IntrinsicPropertyError,
                                              Properties.Resources.LogEntryIntrinsicPropertyNoUnmanagedCodePermissionError);
            }

            try
            {
                threadName = Thread.CurrentThread.Name;
            }
            catch (Exception e)
            {
                threadName = String.Format(Properties.Resources.Culture, Properties.Resources.IntrinsicPropertyError, e.Message);
            }
        }
Esempio n. 26
0
        private void SetSessionVariables(HttpApplication application)
        {
            string queryStringAppPath = string.Empty;
            string queryStringApplicationPhysicalPath = string.Empty;
            string applicationPath         = string.Empty;
            string applicationPhysicalPath = string.Empty;
            string setAppPath     = string.Empty;
            string setAppPhysPath = string.Empty;

            try {
                SecurityPermission permission = new SecurityPermission(PermissionState.Unrestricted);
                permission.Demand();
            } catch {
                Exception permissionException = new Exception((string)HttpContext.GetGlobalResourceObject("GlobalResources", "FullTrustRequired"));
                WebAdminPage.SetCurrentException(application.Context, permissionException);
                application.Server.Transfer("~/error.aspx");
            }

            if (application.Context.Request != null)
            {
                queryStringAppPath = (string)application.Context.Request.QueryString["applicationUrl"];
                queryStringApplicationPhysicalPath = (string)application.Context.Request.QueryString["applicationPhysicalPath"];
            }

            if (application.Context.Session != null)
            {
                if (application.Context.Session[APP_PATH] != null)
                {
                    applicationPath = (string)application.Context.Session[APP_PATH];
                }
                if (application.Context.Session[APP_PHYSICAL_PATH] != null)
                {
                    applicationPhysicalPath = (string)application.Context.Session[APP_PHYSICAL_PATH];
                }
            }

            if ((String.IsNullOrEmpty(queryStringAppPath) && applicationPath == null) ||
                (String.IsNullOrEmpty(queryStringApplicationPhysicalPath) && applicationPhysicalPath == null))
            {
                application.Server.Transfer("~/home0.aspx", false);
                return;
            }

            if (!String.IsNullOrEmpty(queryStringAppPath))
            {
                setAppPath = queryStringAppPath;
            }
            else if (!String.IsNullOrEmpty(applicationPath))
            {
                setAppPath = applicationPath;
            }

            if (!String.IsNullOrEmpty(queryStringApplicationPhysicalPath))
            {
                setAppPhysPath = queryStringApplicationPhysicalPath;
            }
            else if (!String.IsNullOrEmpty(applicationPhysicalPath))
            {
                setAppPhysPath = applicationPhysicalPath;
            }

            if (application.Context.Session != null)
            {
                application.Context.Session[APP_PATH]          = setAppPath;
                application.Context.Session[APP_PHYSICAL_PATH] = setAppPhysPath;
                application.Context.Session[REMOTING_MANAGER]  = new WebAdminRemotingManager(setAppPath, setAppPhysPath, application.Context.Session);
            }
        }
 public static void TestSecurityPermissions()
 {
     Console.WriteLine("\nExecuting TestSecurityPermissions.\n");
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.Assertion);
         Console.WriteLine("Demanding SecurityPermissionFlag.Assertion");
         // This demand should cause an exception.
         sp.Demand();
         // The TestFailed method is called if an exception is not thrown.
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.Assertion failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.ControlAppDomain);
         Console.WriteLine("Demanding SecurityPermissionFlag.ControlAppDomain");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.ControlAppDomain failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.ControlDomainPolicy);
         Console.WriteLine("Demanding SecurityPermissionFlag.ControlDomainPolicy");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.ControlDomainPolicy failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.ControlEvidence);
         Console.WriteLine("Demanding SecurityPermissionFlag.ControlEvidence");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.ControlEvidence failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.ControlPolicy);
         Console.WriteLine("Demanding SecurityPermissionFlag.ControlPolicy");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.ControlPolicy failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.ControlPrincipal);
         Console.WriteLine("Demanding SecurityPermissionFlag.ControlPrincipal");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.ControlPrincipal failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.ControlThread);
         Console.WriteLine("Demanding SecurityPermissionFlag.ControlThread");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.ControlThread failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.Execution);
         Console.WriteLine("Demanding SecurityPermissionFlag.Execution");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.Execution failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.Infrastructure);
         Console.WriteLine("Demanding SecurityPermissionFlag.Infrastructure");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.Infrastructure failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration);
         Console.WriteLine("Demanding SecurityPermissionFlag.RemotingConfiguration");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.RemotingConfiguration failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.SerializationFormatter);
         Console.WriteLine("Demanding SecurityPermissionFlag.SerializationFormatter");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.SerializationFormatter failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.SkipVerification);
         Console.WriteLine("Demanding SecurityPermissionFlag.SkipVerification");
         sp.Demand();
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.SkipVerification failed: " + e.Message);
     }
     try
     {
         SecurityPermission sp =
             new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         Console.WriteLine("Demanding SecurityPermissionFlag.UnmanagedCode");
         // This demand should cause an exception.
         sp.Demand();
         // The TestFailed method is called if an exception is not thrown.
         TestFailed();
     }
     catch (Exception e)
     {
         Console.WriteLine("Demand for SecurityPermissionFlag.UnmanagedCode failed: " + e.Message);
     }
 }
Esempio n. 28
0
        //[ChoSingletonInstanceInitializer]
        public void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            lock (_padLock)
            {
                if (_initialized)
                {
                    return;
                }

                _initialized = true;

                try
                {
                    EntryAssemblyLocation = ChoAssembly.GetEntryAssembly().Location;
                    EntryAssemblyFileName = System.IO.Path.GetFileName(EntryAssemblyLocation);
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                try
                {
                    AppEnvironment = ConfigurationManager.AppSettings["appEnvironment"];
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }

                try
                {
                    SharedEnvironmentConfigFilePath = ConfigurationManager.AppSettings["sharedEnvironmentConfigFilePath"];
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }

                try
                {
                    if (ConfigurationManager.AppSettings["appConfigPath"].IsNullOrWhiteSpace())
                    {
                        ApplicationConfigFilePath = System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
                    }
                    else
                    {
                        ApplicationConfigFilePath = ConfigurationManager.AppSettings["appConfigPath"].Trim();
                    }
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                try
                {
                    ApplicationBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                #region Check for Unmanaged Code Permission Available

                // check whether the unmanaged code permission is available to avoid three potential stack walks
                SecurityPermission unmanagedCodePermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                // avoid a stack walk by checking for the permission on the current assembly. this is safe because there are no
                // stack walk modifiers before the call.
                if (SecurityManager.IsGranted(unmanagedCodePermission))
                {
                    try
                    {
                        unmanagedCodePermission.Demand();
                        UnmanagedCodePermissionAvailable = true;
                    }
                    catch (SecurityException e)
                    {
                        if (ChoTrace.ChoSwitch.TraceError)
                        {
                            Trace.WriteLine(ChoApplicationException.ToString(e));
                        }
                    }
                }

                #endregion Check for Unmanaged Code Permission Available

                EventLogSourceName = ChoApplicationSettings.State.EventLogSourceName;

                #region GetApplicationName

                try
                {
                    ApplicationName = ChoApplicationSettings.State.ApplicationId;
                }
                catch (System.Security.SecurityException ex)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }

                    try
                    {
                        ApplicationName = System.IO.Path.GetFileName(EntryAssemblyLocation);
                    }
                    catch (System.Security.SecurityException e)
                    {
                        ChoTrace.Error(ChoApplicationException.ToString(e));
                    }
                }

                ApplicationNameWithoutExtension = Path.GetFileNameWithoutExtension(ApplicationName);
                if (!ChoApplicationSettings.State.LogFolder.IsNullOrWhiteSpace())
                {
                    ApplicationLogDirectory = ChoApplicationSettings.State.LogFolder;
                }
                else if (ChoApplicationSettings.State.UseApplicationDataFolderAsLogFolder)
                {
                    ApplicationLogDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ApplicationNameWithoutExtension, ChoReservedDirectoryName.Logs);
                }
                else
                {
                    ApplicationLogDirectory = Path.Combine(ApplicationBaseDirectory, ChoReservedDirectoryName.Logs);
                }

                #endregion GetApplicationName

                #region Get AppDomainName

                try
                {
                    AppDomainName = AppDomain.CurrentDomain.FriendlyName;
                }
                catch (Exception ex)
                {
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                }

                #endregion Get AppDomainName

                #region Get ProcessId, ProcessName

                if (UnmanagedCodePermissionAvailable)
                {
                    try
                    {
                        ProcessId = ChoKernel32Core.GetCurrentProcessId();
                    }
                    catch (Exception ex)
                    {
                        if (ChoTrace.ChoSwitch.TraceError)
                        {
                            Trace.WriteLine(ex.ToString());
                        }
                    }

                    try
                    {
                        ProcessFilePath = GetProcessName();
                    }
                    catch (Exception ex)
                    {
                        if (ChoTrace.ChoSwitch.TraceError)
                        {
                            Trace.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    if (ChoTrace.ChoSwitch.TraceError)
                    {
                        Trace.WriteLine("Failed to retrieve value due to unmanaged code permission denied.");
                    }
                }

                #endregion Get ProcessId, ProcessName

                #region Get HostName

                // Get the DNS host name of the current machine
                try
                {
                    // Lookup the host name
                    HostName = System.Net.Dns.GetHostName();
                }
                catch (System.Net.Sockets.SocketException)
                {
                }
                catch (System.Security.SecurityException)
                {
                    // We may get a security exception looking up the hostname
                    // You must have Unrestricted DnsPermission to access resource
                }

                // Get the NETBIOS machine name of the current machine
                if (HostName.IsNullOrWhiteSpace())
                {
                    try
                    {
                        HostName = Environment.MachineName;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                    catch (System.Security.SecurityException)
                    {
                        // We may get a security exception looking up the machine name
                        // You must have Unrestricted EnvironmentPermission to access resource
                    }
                }

                #endregion Get HostName

                ApplyFrxParamsOverrides.Raise(this, null);
            }
        }
Esempio n. 29
0
        /// <include file='doc\SoapServerVroot.uex' path='docs/doc[@for="SoapServerVRoot.CreateVirtualRootEx"]/*' />
        public void CreateVirtualRootEx(
            string rootWebServer,
            string inBaseUrl,
            string inVirtualRoot,
            string homePage,
            string discoFile,
            string secureSockets,
            string authentication,
            string operation,
            out string baseUrl,
            out string virtualRoot,
            out string physicalPath
            )
        {
            // if Operation if an empty string, the VRoot will be published
            baseUrl      = "";
            virtualRoot  = "";
            physicalPath = "";
            bool bSSL         = true;
            bool bWindowsAuth = true;
            bool bAnonymous   = false;
            bool bDiscoFile   = false;
            bool bHomePage    = false;
            bool bImpersonate = true;

            try
            {
                SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                sp.Demand();
                Platform.Assert(Platform.Whistler, "SoapServerVRoot.CreateVirtualRootEx");
                if (inBaseUrl.Length <= 0 && inVirtualRoot.Length <= 0)
                {
                    return;
                }
                string rootWeb = "IIS://localhost/W3SVC/1/ROOT";
                if (rootWebServer.Length > 0)
                {
                    rootWeb = rootWebServer;
                }
                if (authentication.ToLower(CultureInfo.InvariantCulture) == "anonymous")
                {
                    bAnonymous   = true;
                    bWindowsAuth = false;
                    bImpersonate = false;
                }
                bDiscoFile = SoapServerInfo.BoolFromString(discoFile, bDiscoFile);
                bHomePage  = SoapServerInfo.BoolFromString(homePage, bHomePage);
                bSSL       = SoapServerInfo.BoolFromString(secureSockets, bSSL);
                string protocol = "https";
                if (!bSSL)
                {
                    protocol = "http";
                }
                SoapServerInfo.ParseUrl(inBaseUrl, inVirtualRoot, protocol, out baseUrl, out virtualRoot);
                physicalPath = SoapServerInfo.ServerPhysicalPath(rootWeb, inBaseUrl, inVirtualRoot, true);
                SoapServerConfig.Create(physicalPath, bImpersonate, bWindowsAuth);
                if (bDiscoFile)
                {
                    DiscoFile webDisco = new DiscoFile();
                    webDisco.Create(physicalPath, "Default.disco");
                }
                else
                {
                    if (File.Exists(physicalPath + "\\Default.disco"))
                    {
                        File.Delete(physicalPath + "\\Default.disco");
                    }
                }
                if (bHomePage)
                {
                    HomePage webPage       = new HomePage();
                    string   discoFileName = "";
                    if (bDiscoFile)
                    {
                        discoFileName = "Default.disco";
                    }
                    webPage.Create(physicalPath, virtualRoot, "Default.aspx", discoFileName);
                }
                else
                {
                    if (File.Exists(physicalPath + "\\Default.aspx"))
                    {
                        File.Delete(physicalPath + "\\Default.aspx");
                    }
                }
                IISVirtualRootEx.CreateOrModify(rootWeb, physicalPath, virtualRoot, bSSL, bWindowsAuth, bAnonymous, bHomePage);
            }
            catch
            {
                string etxt = Resource.FormatString("Soap_VRootCreationFailed");
                ComSoapPublishError.Report(etxt + " " + virtualRoot);
                throw;
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Removes user from reference list and frees the 7-zip library if it becomes empty
        /// </summary>
        /// <param name="user">Caller of the function</param>
        /// <param name="format">Archive format</param>
        public static void FreeLibrary(object user, Enum format)
        {
            var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            sp.Demand();

            lock (_syncRoot)
            {
                if (_modulePtr != IntPtr.Zero)
                {
                    if (format is InArchiveFormat archiveFormat)
                    {
                        if (_inArchives != null && _inArchives.ContainsKey(user) &&
                            _inArchives[user].ContainsKey(archiveFormat) &&
                            _inArchives[user][archiveFormat] != null)
                        {
                            try
                            {
                                Marshal.ReleaseComObject(_inArchives[user][archiveFormat]);
                            }
                            catch (InvalidComObjectException) {}
                            _inArchives[user].Remove(archiveFormat);
                            _totalUsers--;
                            if (_inArchives[user].Count == 0)
                            {
                                _inArchives.Remove(user);
                            }
                        }
                    }
#if COMPRESS
                    if (format is OutArchiveFormat outArchiveFormat)
                    {
                        if (_outArchives != null && _outArchives.ContainsKey(user) &&
                            _outArchives[user].ContainsKey(outArchiveFormat) &&
                            _outArchives[user][outArchiveFormat] != null)
                        {
                            try
                            {
                                Marshal.ReleaseComObject(_outArchives[user][outArchiveFormat]);
                            }
                            catch (InvalidComObjectException) {}
                            _outArchives[user].Remove(outArchiveFormat);
                            _totalUsers--;
                            if (_outArchives[user].Count == 0)
                            {
                                _outArchives.Remove(user);
                            }
                        }
                    }
#endif
                    if ((_inArchives == null || _inArchives.Count == 0)
#if COMPRESS
                        && (_outArchives == null || _outArchives.Count == 0)
#endif
                        )
                    {
                        _inArchives = null;
#if COMPRESS
                        _outArchives = null;
#endif
                        if (_totalUsers == 0)
                        {
                            NativeMethods.FreeLibrary(_modulePtr);
                            _modulePtr = IntPtr.Zero;
                        }
                    }
                }
            }
        }
//<Snippet18>
    public static void DemandSecurityPermissions()
    {
        Console.WriteLine("\nExecuting DemandSecurityPermissions.\n");
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.Assertion);
            Console.WriteLine("Demanding SecurityPermissionFlag.Assertion");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.Assertion succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.Assertion failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.ControlAppDomain);
            Console.WriteLine("Demanding SecurityPermissionFlag.ControlAppDomain");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlAppDomain succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlAppDomain failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.ControlDomainPolicy);
            Console.WriteLine("Demanding SecurityPermissionFlag.ControlDomainPolicy");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlDomainPolicy succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlDomainPolicy failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.ControlEvidence);
            Console.WriteLine("Demanding SecurityPermissionFlag.ControlEvidence");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlEvidence succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlEvidence failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.ControlPolicy);
            Console.WriteLine("Demanding SecurityPermissionFlag.ControlPolicy");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlPolicy succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlPolicy failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.ControlPrincipal);
            Console.WriteLine("Demanding SecurityPermissionFlag.ControlPrincipal");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlPrincipal succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlPrincipal failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.ControlThread);
            Console.WriteLine("Demanding SecurityPermissionFlag.ControlThread");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlThread succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.ControlThread failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.Execution);
            Console.WriteLine("Demanding SecurityPermissionFlag.Execution");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.Execution succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.Execution failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.Infrastructure);
            Console.WriteLine("Demanding SecurityPermissionFlag.Infrastructure");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.Infrastructure succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.Infrastructure failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration);
            Console.WriteLine("Demanding SecurityPermissionFlag.RemotingConfiguration");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.RemotingConfiguration succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.RemotingConfiguration failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.SerializationFormatter);
            Console.WriteLine("Demanding SecurityPermissionFlag.SerializationFormatter");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.SerializationFormatter succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.SerializationFormatter failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.SkipVerification);
            Console.WriteLine("Demanding SecurityPermissionFlag.SkipVerification");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.SkipVerification succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.SkipVerification failed: " + e.Message);
        }
        try
        {
            SecurityPermission sp =
                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            Console.WriteLine("Demanding SecurityPermissionFlag.UnmanagedCode");
            sp.Demand();
            Console.WriteLine("Demand for SecurityPermissionFlag.UnmanagedCode succeeded.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Demand for SecurityPermissionFlag.UnmanagedCode failed: " + e.Message);
        }
    }