public Clerk(string compensator, string description, CompensatorOptions flags)
 {
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     permission.Demand();
     permission.Assert();
     this.Init(compensator, description, flags);
 }
Esempio n. 2
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 ClerkMonitor()
 {
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     permission.Demand();
     permission.Assert();
     this._monitor = new CrmMonitor();
     this._version = 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);
 }
	public void Assert()
			{
				// We must have the "Assertion" security flag for this to work.
				SecurityPermission perm;
				perm = new SecurityPermission(SecurityPermissionFlag.Assertion);
				perm.Demand();

				// Assert this permission.
				Assert(2);
			}
Esempio n. 6
0
 internal static void AnimateWindow(Control control, int time, AnimationFlags flags)
 {
     try
     {
         SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         sp.Demand();
         AnimateWindow(new HandleRef(control, control.Handle), time, flags);
     }
     catch (SecurityException) { }
 }
        internal static void AnimateWindow(Control control, int time, AnimationFlags flags)
        {
            Contract.Requires<ArgumentNullException>(control != null);

            try
            {
                SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                sp.Demand();
                AnimateWindow(new HandleRef(control, control.Handle), time, flags);
            }
            catch (SecurityException) { }
        }
Esempio n. 8
0
 internal static void AnimateWindow(Control control, int time, NativeMethods.AnimationFlags flags)
 {
     try
     {
         System.Security.Permissions.SecurityPermission securityPermission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode);
         securityPermission.Demand();
         NativeMethods.AnimateWindow(new System.Runtime.InteropServices.HandleRef(control, control.Handle), time, flags);
     }
     catch (System.Security.SecurityException)
     {
     }
 }
 public void DoWork()
 {
     // Note that because DoDangerousThing is public, this
      // security check does not resolve the violation.
      // This only checks callers that go through DoWork().
      SecurityPermission secPerm = new SecurityPermission(
     SecurityPermissionFlag.ControlPolicy |
     SecurityPermissionFlag.ControlEvidence
      );
      secPerm.Demand();
      DoDangerousThing();
 }
Esempio n. 10
0
 internal static void SetTopMost(Control control)
 {
     try
     {
         System.Security.Permissions.SecurityPermission securityPermission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode);
         securityPermission.Demand();
         NativeMethods.SetWindowPos(new System.Runtime.InteropServices.HandleRef(control, control.Handle), NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, 19);
     }
     catch (System.Security.SecurityException)
     {
     }
 }
Esempio n. 11
0
 /// <summary>
 /// Static Constructor is used to set the CanBinarySerialize value only once for the given security policy
 /// </summary>
 static Serializer()
 {
     SecurityPermission sp =  new SecurityPermission(SecurityPermissionFlag.SerializationFormatter);
     try
     {
         sp.Demand();
         CanBinarySerialize = true;
     }
     catch(SecurityException)
     {
         CanBinarySerialize = false;
     }
 }
		/// <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;
		}
        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. 14
0
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            try
            {
                SecurityPermission permission =
                    new SecurityPermission(PermissionState.Unrestricted);
                permission.Demand();
            }
            catch (SecurityException)
            {
                throw new InstallException(
                    "You have insufficient privileges to " +
                    "install the add-in into the ClickOnce cache. " +
                    "Please contact your system administrator.");
            }
            string deploymentLocation = Context.Parameters["deploymentLocation"];
            if (String.IsNullOrEmpty(deploymentLocation))
            {
                throw new InstallException("Deployment location not configured. Setup unable to continue");
            }

            string arguments = String.Format(
                "/S /I \"{0}\"", deploymentLocation);

            int exitCode = ExecuteVSTOInstaller(arguments);
            if (exitCode != 0)
            {
                string message = null;
                switch (exitCode)
                {
                    case -300:
                        message = String.Format(
                            "The Visual Studio Tools for Office solution was signed by an untrusted publisher and as such cannot be installed automatically. Please use your browser to navigate to {0} in order to install the solution manually. You will be prompted if the solution is trusted for execution.",
                            deploymentLocation);
                        break;
                    default:
                        message = String.Format(
                            "The installation of the ClickOnce solution failed with exit code {0}",
                            exitCode);
                        break;
                }
                throw new InstallException(message);
            }
            stateSaver.Add("deploymentLocation", deploymentLocation);
            base.Install(stateSaver);
        }
Esempio n. 15
0
        private static void GetPermissions()
        {
            if (!m_Initialized)
            {
                //test RelectionPermission
                CodeAccessPermission securityTest;
                try
                {
                    securityTest = new ReflectionPermission(PermissionState.Unrestricted);
                    securityTest.Demand();
                    m_ReflectionPermission = true;
                }
                catch
                {
                    //code access security error
                    m_ReflectionPermission = false;
                }
				
                //test WebPermission
                try
                {
                    securityTest = new WebPermission(PermissionState.Unrestricted);
                    securityTest.Demand();
                    m_WebPermission = true;
                }
                catch
                {
                    //code access security error
                    m_WebPermission = false;
                }
				
                //test WebHosting Permission (Full Trust)
                try
                {
                    securityTest = new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted);
                    securityTest.Demand();
                    m_AspNetHostingPermission = true;
                }
                catch
                {
                    //code access security error
                    m_AspNetHostingPermission = false;
                }
                m_Initialized = true;

                //Test for Unmanaged Code permission
                try
                {
                    securityTest = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                    securityTest.Demand();
                    m_UnManagedCodePermission = true;
                }
                catch (Exception e)
                {
                    m_UnManagedCodePermission = false;
                }
            }
        }
        /// <summary>
        /// Sets the compression properties
        /// </summary>
        private void SetCompressionProperties()
        {
            switch (_archiveFormat)
            {
                case OutArchiveFormat.Tar:
                    break;
                default:
                    ISetProperties setter = CompressionMode == CompressionMode.Create && _updateData.FileNamesToModify == null
                                            ? (ISetProperties)SevenZipLibraryManager.OutArchive(
                                                    _archiveFormat, this)
                                            : (ISetProperties)SevenZipLibraryManager.InArchive(
                                                    Formats.InForOutFormats[_archiveFormat], this);
                    if (setter == null)
                    {
                        if (!ThrowException(null,
                                            new CompressionFailedException(
                                                "The specified archive format is unsupported.")))
                        {
                            return;
                        }
                    }
                    if (_volumeSize > 0 && ArchiveFormat != OutArchiveFormat.SevenZip)
                    {
                        throw new CompressionFailedException("Unfortunately, the creation of multivolume non-7Zip archives is not implemented. It will be one day, though.");
                    }
                    if (CustomParameters.ContainsKey("x") || CustomParameters.ContainsKey("m"))
                    {
                        if (
                            !ThrowException(null,
                                            new CompressionFailedException(
                                                "The specified compression parameters are invalid.")))
                        {
                            return;
                        }
                    }
                    var names = new List<IntPtr>(2 + CustomParameters.Count);
                    var values = new List<PropVariant>(2 + CustomParameters.Count);
#if !WINCE
                    var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                    sp.Demand();
#endif
                    #region Initialize compression properties

                    if (_compressionMethod == CompressionMethod.Default)
                    {
                        names.Add(Marshal.StringToBSTR("x"));
                        values.Add(new PropVariant());
                        foreach (var pair in CustomParameters)
                        {
                            names.Add(Marshal.StringToBSTR(pair.Key));
                            var pv = new PropVariant();
                            if (pair.Key == "fb" || pair.Key == "pass" || pair.Key == "d")
                            {
                                pv.VarType = VarEnum.VT_UI4;
                                pv.UInt32Value = Convert.ToUInt32(pair.Value, CultureInfo.InvariantCulture);
                            }
                            else
                            {
                                pv.VarType = VarEnum.VT_BSTR;
                                pv.Value = Marshal.StringToBSTR(pair.Value);
                            }
                            values.Add(pv);
                        }
                    }
                    else
                    {
                        names.Add(Marshal.StringToBSTR("x"));
                        names.Add(_archiveFormat == OutArchiveFormat.Zip
                                      ? Marshal.StringToBSTR("m")
                                      : Marshal.StringToBSTR("0"));
                        values.Add(new PropVariant());
                        var pv = new PropVariant
                        {
                            VarType = VarEnum.VT_BSTR,
                            Value = Marshal.StringToBSTR(Formats.MethodNames[_compressionMethod])
                        };
                        values.Add(pv);
                        foreach (var pair in CustomParameters)
                        {
                            names.Add(Marshal.StringToBSTR(pair.Key));
                            pv = new PropVariant();
                            if (pair.Key == "fb" || pair.Key == "pass" || pair.Key == "d")
                            {
                                pv.VarType = VarEnum.VT_UI4;
                                pv.UInt32Value = Convert.ToUInt32(pair.Value, CultureInfo.InvariantCulture);
                            }
                            else
                            {
                                pv.VarType = VarEnum.VT_BSTR;
                                pv.Value = Marshal.StringToBSTR(pair.Value);
                            }
                            values.Add(pv);
                        }
                    }

                    #endregion

                    #region Set compression level

                    PropVariant clpv = values[0];
                    clpv.VarType = VarEnum.VT_UI4;
                    switch (CompressionLevel)
                    {
                        case CompressionLevel.None:
                            clpv.UInt32Value = 0;
                            break;
                        case CompressionLevel.Fast:
                            clpv.UInt32Value = 1;
                            break;
                        case CompressionLevel.Low:
                            clpv.UInt32Value = 3;
                            break;
                        case CompressionLevel.Normal:
                            clpv.UInt32Value = 5;
                            break;
                        case CompressionLevel.High:
                            clpv.UInt32Value = 7;
                            break;
                        case CompressionLevel.Ultra:
                            clpv.UInt32Value = 9;
                            break;
                    }
                    values[0] = clpv;

                    #endregion

                    #region Encrypt headers

                    if (EncryptHeaders && _archiveFormat == OutArchiveFormat.SevenZip &&
                        !SwitchIsInCustomParameters("he"))
                    {
                        names.Add(Marshal.StringToBSTR("he"));
                        var tmp = new PropVariant { VarType = VarEnum.VT_BSTR, Value = Marshal.StringToBSTR("on") };
                        values.Add(tmp);
                    }

                    #endregion

                    #region Zip Encryption

                    if (_archiveFormat == OutArchiveFormat.Zip && ZipEncryptionMethod != ZipEncryptionMethod.ZipCrypto &&
                        !SwitchIsInCustomParameters("em"))
                    {
                        names.Add(Marshal.StringToBSTR("em"));
                        var tmp = new PropVariant
                        {
                            VarType = VarEnum.VT_BSTR,
                            Value = Marshal.StringToBSTR(
#if !WINCE
Enum.GetName(typeof(ZipEncryptionMethod), ZipEncryptionMethod))
#else
                            OpenNETCF.Enum2.GetName(typeof (ZipEncryptionMethod), ZipEncryptionMethod))
#endif
                        };
                        values.Add(tmp);
                    }

                    #endregion

                    var namesHandle = GCHandle.Alloc(names.ToArray(), GCHandleType.Pinned);
                    var valuesHandle = GCHandle.Alloc(values.ToArray(), GCHandleType.Pinned);
                    try
                    {
                        if (setter != null) //ReSharper
                            setter.SetProperties(namesHandle.AddrOfPinnedObject(), valuesHandle.AddrOfPinnedObject(),
                                                 names.Count);
                    }
                    finally
                    {
                        namesHandle.Free();
                        valuesHandle.Free();
                    }
                    break;
            }
        }
 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. 19
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);
            }
        }
Esempio n. 20
0
 internal DataAccessObject()
 {
     SecurityPermission perm = new SecurityPermission(PermissionState.Unrestricted);
     perm.Demand();
 }
Esempio n. 21
0
 internal static void SetTopMost(Control control)
 {
     try
     {
         var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
         sp.Demand();
         SetWindowPos(new HandleRef(control, control.Handle), HWND_TOPMOST, 0, 0, 0, 0, 0x13);
     }
     catch (SecurityException) { }
 }
        /// <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)
        {
            #if !WINCE && !MONO
            var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            sp.Demand();
            #endif
            lock (_syncRoot)
            {
                if (_modulePtr != IntPtr.Zero)
            {
                if (format is InArchiveFormat)
                {
                    if (_inArchives != null && _inArchives.ContainsKey(user) &&
                        _inArchives[user].ContainsKey((InArchiveFormat) format) &&
                        _inArchives[user][(InArchiveFormat) format] != null)
                    {
                        try
                        {
                            Marshal.ReleaseComObject(_inArchives[user][(InArchiveFormat) format]);
                        }
                        catch (InvalidComObjectException) {}
                        _inArchives[user].Remove((InArchiveFormat) format);
                        _totalUsers--;
                        if (_inArchives[user].Count == 0)
                        {
                            _inArchives.Remove(user);
                        }
                    }
                }
            #if COMPRESS
                if (format is OutArchiveFormat)
                {
                    if (_outArchives != null && _outArchives.ContainsKey(user) &&
                        _outArchives[user].ContainsKey((OutArchiveFormat) format) &&
                        _outArchives[user][(OutArchiveFormat) format] != null)
                    {
                        try
                        {
                            Marshal.ReleaseComObject(_outArchives[user][(OutArchiveFormat) format]);
                        }
                        catch (InvalidComObjectException) {}
                        _outArchives[user].Remove((OutArchiveFormat) format);
                        _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)
                    {
            #if !WINCE && !MONO
                        NativeMethods.FreeLibrary(_modulePtr);

            #endif
                        _modulePtr = IntPtr.Zero;
                    }
                }
            }
            }
        }
 static void DemandException(SecurityPermission denyPermission)
 {
     denyPermission.Demand();
 }
 /// <summary>
 /// Creates a base Api, this is the building block from which all the other apis need the interraction methods.
 /// You cannot create this object from a script, it is supplied to you in the 'api' property
 /// </summary>
 /// <exception cref="System.Security.SecurityException"/>
 internal InteractionObject()
 {
     SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     perm.Demand();
 }
        public override object GetEditor(Type editorBaseType)
        {
            SecurityPermission MyPermission = new SecurityPermission(PermissionState.Unrestricted);
            MyPermission.Demand();

            return new RuleSetDefinitionEditor();
        }
Esempio n. 26
0
		/// <summary>
		/// This method will return the user account name and domain name based on the
		/// SID
		/// </summary>
		/// <param name="sid">SID to search on.</param>
		/// <returns>Domain[BuiltIn] Name\User Name related to the SID</returns>
		public static string GetUserAccount(byte[] sid)
		{
			int err = NativeMethods.NoError;
			byte[] sidTest = null;
			StringBuilder sidName = new StringBuilder();
			uint cchName = (uint) sidName.Capacity;
			StringBuilder domainName = new StringBuilder();
			uint cchDomain = (uint) domainName.Capacity;
			SidNameUseType sidType;
			if (sid == null)
			{
				err = NativeMethods.ErrorInvalidParameter;
			}
			else
			{
				// Check if it needs converting.
				if (sid[0] == 48)
				{
					// Convert the SID that is passed in to the correct format.
					sidTest = new byte[sid.Length / 2];
					StringBuilder pair = new StringBuilder();
					int j = 0;
					for (int i = 0; i < sid.Length; i++)
					{
						pair.Remove(0, pair.Length);
						pair.AppendFormat("0x{0}{1}", Convert.ToChar(sid[i]), Convert.ToChar(sid[i + 1]));
						i++;
						sidTest[j++] = Convert.ToByte(pair.ToString(), 16);
					}
				}
				else
				{
					sidTest = sid;
				}
				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.Demand();
				//Lookup the account and use both the local as well as the domain				
				if (!NativeMethods.LookupAccountSid(null, sidTest, sidName, ref cchName, domainName, ref cchDomain, out sidType))
				{
					err = Marshal.GetLastWin32Error();
					if (err == NativeMethods.ErrorInsufficientBuffer)
					{
						sidName.EnsureCapacity((int) cchName);
						domainName.EnsureCapacity((int) cchDomain);
						err = NativeMethods.NoError;
						if (!NativeMethods.LookupAccountSid(null, sid, sidName, ref cchName, domainName, ref cchDomain, out sidType))
						{
							err = Marshal.GetLastWin32Error();
						}
					}
				}
			}

			StringBuilder res = new StringBuilder();
			if (err == NativeMethods.NoError)
			{
				res.AppendFormat("{0}\\{1}", domainName.ToString(), sidName.ToString());
			}
			return res.ToString();
		}
 /// <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 !WINCE && !MONO
             var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
             sp.Demand();
             if (_modulePtr == IntPtr.Zero)
             {
                 throw new SevenZipLibraryException();
             }
             var createObject = (NativeMethods.CreateObjectDelegate)
                 Marshal.GetDelegateForFunctionPointer(
                     NativeMethods.GetProcAddress(_modulePtr, "CreateObject"),
                     typeof(NativeMethods.CreateObjectDelegate));
             if (createObject == null)
             {
                 throw new SevenZipLibraryException();
             }
     #endif
             object result;
             Guid interfaceId =
     #if !WINCE && !MONO
      typeof(IOutArchive).GUID;
     #else
             new Guid(((GuidAttribute)typeof(IOutArchive).GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value);
     #endif
             Guid classID = Formats.OutFormatGuids[format];
             try
             {
     #if !WINCE && !MONO
                 createObject(ref classID, ref interfaceId, out result);
     #elif !MONO
                 NativeMethods.CreateCOMObject(ref classID, ref interfaceId, out result);
     #else
                 result = SevenZip.Mono.Factory.CreateInterface<IOutArchive>(classID, interfaceId, user);
     #endif
             }
             catch (Exception)
             {
                 throw new SevenZipLibraryException("Your 7-zip library does not support this archive type.");
             }
             InitUserOutFormat(user, format);
             _outArchives[user][format] = result as IOutArchive;
         }
         return _outArchives[user][format];
     #if !WINCE && !MONO
     }
     #endif
 }
	// Constructor.
	public ObjectManager(ISurrogateSelector selector,
						 StreamingContext context)
			{
				// Make sure that we have the correct permissions.
				SecurityPermission perm = new SecurityPermission
					(SecurityPermissionFlag.SerializationFormatter);
				perm.Demand();

				// Initialize the object manager.
				this.selector = selector;
				this.context = context;
				this.objects = new Hashtable(16); // avoid expanding of hashtable
				this.callbackList = new ArrayList();
			}
Esempio n. 29
0
 internal RS3()
 {
     SecurityPermission perm = new SecurityPermission(PermissionState.Unrestricted);
     perm.Demand();
 }
        internal static void SetTopMost(Control control)
        {
            Contract.Requires<ArgumentNullException>(control != null);

            try
            {
                SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                sp.Demand();
                SetWindowPos(new HandleRef(control, control.Handle), HWND_TOPMOST, 0, 0, 0, 0, 0x13);
            }
            catch (SecurityException) { }
        }
Esempio n. 31
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;
            }
        }
 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);
 }