Demand() public method

public Demand ( ) : void
return void
示例#1
0
        internal unsafe static void ReflectedLinkDemandInvoke(MethodBase mb)
        {
            RuntimeDeclSecurityActions runtimeDeclSecurityActions;
            RuntimeDeclSecurityActions runtimeDeclSecurityActions2;

            if (!SecurityManager.GetLinkDemandSecurity(mb, &runtimeDeclSecurityActions, &runtimeDeclSecurityActions2))
            {
                return;
            }
            PermissionSet permissionSet = null;

            if (runtimeDeclSecurityActions.cas.size > 0)
            {
                permissionSet = SecurityManager.Decode(runtimeDeclSecurityActions.cas.blob, runtimeDeclSecurityActions.cas.size);
            }
            if (runtimeDeclSecurityActions.noncas.size > 0)
            {
                PermissionSet permissionSet2 = SecurityManager.Decode(runtimeDeclSecurityActions.noncas.blob, runtimeDeclSecurityActions.noncas.size);
                permissionSet = ((permissionSet != null) ? permissionSet.Union(permissionSet2) : permissionSet2);
            }
            if (runtimeDeclSecurityActions2.cas.size > 0)
            {
                PermissionSet permissionSet3 = SecurityManager.Decode(runtimeDeclSecurityActions2.cas.blob, runtimeDeclSecurityActions2.cas.size);
                permissionSet = ((permissionSet != null) ? permissionSet.Union(permissionSet3) : permissionSet3);
            }
            if (runtimeDeclSecurityActions2.noncas.size > 0)
            {
                PermissionSet permissionSet4 = SecurityManager.Decode(runtimeDeclSecurityActions2.noncas.blob, runtimeDeclSecurityActions2.noncas.size);
                permissionSet = ((permissionSet != null) ? permissionSet.Union(permissionSet4) : permissionSet4);
            }
            if (permissionSet != null)
            {
                permissionSet.Demand();
            }
        }
 public bool Build(X509Certificate2 certificate)
 {
     lock (this.m_syncRoot)
     {
         if ((certificate == null) || certificate.CertContext.IsInvalid)
         {
             throw new ArgumentException(SR.GetString("Cryptography_InvalidContextHandle"), "certificate");
         }
         new StorePermission(StorePermissionFlags.EnumerateCertificates | StorePermissionFlags.OpenStore).Demand();
         X509ChainPolicy chainPolicy = this.ChainPolicy;
         if ((chainPolicy.RevocationMode == X509RevocationMode.Online) && ((certificate.Extensions["2.5.29.31"] != null) || (certificate.Extensions["1.3.6.1.5.5.7.1.1"] != null)))
         {
             PermissionSet set = new PermissionSet(PermissionState.None);
             set.AddPermission(new WebPermission(PermissionState.Unrestricted));
             set.AddPermission(new StorePermission(StorePermissionFlags.AddToStore));
             set.Demand();
         }
         this.Reset();
         if (BuildChain(this.m_useMachineContext ? new IntPtr(1L) : new IntPtr(0L), certificate.CertContext, chainPolicy.ExtraStore, chainPolicy.ApplicationPolicy, chainPolicy.CertificatePolicy, chainPolicy.RevocationMode, chainPolicy.RevocationFlag, chainPolicy.VerificationTime, chainPolicy.UrlRetrievalTimeout, ref this.m_safeCertChainHandle) != 0)
         {
             return false;
         }
         this.Init();
         CAPIBase.CERT_CHAIN_POLICY_PARA pPolicyPara = new CAPIBase.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPIBase.CERT_CHAIN_POLICY_PARA)));
         CAPIBase.CERT_CHAIN_POLICY_STATUS pPolicyStatus = new CAPIBase.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPIBase.CERT_CHAIN_POLICY_STATUS)));
         pPolicyPara.dwFlags = (uint) chainPolicy.VerificationFlags;
         if (!CAPISafe.CertVerifyCertificateChainPolicy(new IntPtr(1L), this.m_safeCertChainHandle, ref pPolicyPara, ref pPolicyStatus))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
         CAPISafe.SetLastError(pPolicyStatus.dwError);
         return (pPolicyStatus.dwError == 0);
     }
 }
示例#3
0
        public int Fill(DataSet dataSet, object ADODBRecordSet, string srcTable)
        {
            System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
            permissionSet.AddPermission(OleDbConnection.ExecutePermission); // MDAC 77737
            permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode));
            permissionSet.Demand();

            IntPtr hscp;

            Bid.ScopeEnter(out hscp, "<oledb.OleDbDataAdapter.Fill|API> %d#, dataSet, ADODBRecordSet, srcTable='%ls'\n", ObjectID, srcTable);
            try {
                if (null == dataSet)
                {
                    throw ADP.ArgumentNull("dataSet");
                }
                if (null == ADODBRecordSet)
                {
                    throw ADP.ArgumentNull("adodb");
                }
                if (ADP.IsEmpty(srcTable))
                {
                    throw ADP.FillRequiresSourceTableName("srcTable");
                }
                // user was required to have UnmanagedCode Permission just to create ADODB
                // (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand();
                return(FillFromADODB((object)dataSet, ADODBRecordSet, srcTable, true));
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }
        public void SetMethod()
        {
            ReflectionPermission          rp  = new ReflectionPermission(ReflectionPermissionFlag.AllFlags);
            IsolatedStorageFilePermission isp = new IsolatedStorageFilePermission(PermissionState.Unrestricted);

            System.Security.PermissionSet ps = new System.Security.PermissionSet(PermissionState.None);
            ps.AddPermission(rp);
            ps.AddPermission(isp);
            ps.Demand();
        }
示例#5
0
        public void Demand()
        {
            // check all collection in a single stack walk
            PermissionSet superset = new PermissionSet(PermissionState.None);

            foreach (PermissionSet ps in _list)
            {
                foreach (IPermission p in ps)
                {
                    superset.AddPermission(p);
                }
            }
            superset.Demand();
        }
示例#6
0
      protected AppDomainHost(Type serviceType,AppDomain appDomain,PermissionSet permissions,Uri[] baseAddresses)
      {
         State = CommunicationState.Faulted;

         //Cannot grant service permissions the host does not have
         permissions.Demand();

         string assemblyName = Assembly.GetAssembly(typeof(ServiceHostActivator)).FullName;
         m_ServiceHostActivator = appDomain.CreateInstanceAndUnwrap(assemblyName,typeof(ServiceHostActivator).ToString()) as ServiceHostActivator;

         appDomain.SetPermissionsSet(permissions);

         m_ServiceHostActivator.CreateHost(serviceType,baseAddresses);

         State = CommunicationState.Created;
      }      
        public void CanAllowConnectionAfterPermitOnlyPermission()
        {
            PermissionSet permissionset = new PermissionSet(PermissionState.None);

              MySqlClientPermission permission = new MySqlClientPermission(PermissionState.None);

              MySqlConnectionStringBuilder strConn = new MySqlConnectionStringBuilder(conn.ConnectionString);

              //// Allow connections only to specified database no additional optional parameters
              permission.Add("server=localhost;User Id=root;database=" + strConn.Database + ";port=" + strConn.Port + ";", "", KeyRestrictionBehavior.PreventUsage);
              permission.PermitOnly();
              permissionset.AddPermission(permission);
              permissionset.Demand();

              // this conection should be allowed
              MySqlConnection dummyconn = new MySqlConnection();
              dummyconn.ConnectionString = "server=localhost;User Id=root;database=" + strConn.Database + ";port=" + strConn.Port + ";includesecurityasserts=true;";
              dummyconn.Open();
              if (dummyconn.State == ConnectionState.Open) dummyconn.Close();
        }
示例#8
0
        // When using reflection LinkDemand are promoted to full Demand (i.e. stack walk)
        internal unsafe static void ReflectedLinkDemandInvoke(MethodBase mb)
        {
            RuntimeDeclSecurityActions klass;
            RuntimeDeclSecurityActions method;

            if (!GetLinkDemandSecurity(mb, &klass, &method))
            {
                return;
            }

            PermissionSet ps = null;

            if (klass.cas.size > 0)
            {
                ps = Decode(klass.cas.blob, klass.cas.size);
            }
            if (klass.noncas.size > 0)
            {
                PermissionSet p = Decode(klass.noncas.blob, klass.noncas.size);
                ps = (ps == null) ? p : ps.Union(p);
            }

            if (method.cas.size > 0)
            {
                PermissionSet p = Decode(method.cas.blob, method.cas.size);
                ps = (ps == null) ? p : ps.Union(p);
            }
            if (method.noncas.size > 0)
            {
                PermissionSet p = Decode(method.noncas.blob, method.noncas.size);
                ps = (ps == null) ? p : ps.Union(p);
            }

            // in this case we union-ed the permission sets because we want to do
            // a single stack walk (not up to 4).
            if (ps != null)
            {
                ps.Demand();
            }
        }
示例#9
0
        static void loadAssembly2()
        {
            Assembly assembly = Assembly.LoadFrom("assembly2.dll");

            Console.WriteLine("Strong Name : " + assembly.GetName());
            try
            {
                PermissionSet perr = new PermissionSet(PermissionState.None);

                perr.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

                perr.PermitOnly();
                perr.Demand();

                Assembly2.AssemblyClass2.openPage();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

            }
        }
 public int Fill(DataSet dataSet, object ADODBRecordSet, string srcTable)
 {
     int num;
     IntPtr ptr;
     PermissionSet set = new PermissionSet(PermissionState.None);
     set.AddPermission(OleDbConnection.ExecutePermission);
     set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
     set.Demand();
     Bid.ScopeEnter(out ptr, "<oledb.OleDbDataAdapter.Fill|API> %d#, dataSet, ADODBRecordSet, srcTable='%ls'\n", base.ObjectID, srcTable);
     try
     {
         if (dataSet == null)
         {
             throw ADP.ArgumentNull("dataSet");
         }
         if (ADODBRecordSet == null)
         {
             throw ADP.ArgumentNull("adodb");
         }
         if (ADP.IsEmpty(srcTable))
         {
             throw ADP.FillRequiresSourceTableName("srcTable");
         }
         num = this.FillFromADODB(dataSet, ADODBRecordSet, srcTable, true);
     }
     finally
     {
         Bid.ScopeLeave(ref ptr);
     }
     return num;
 }
示例#11
0
 /// <summary>
 /// Gets the service control permission.
 /// </summary>
 /// <param name="svc">The SVC.</param>
 /// <returns></returns>
 /// <exception cref="System.Security.SecurityException">when the permission cannot be acquired</exception>
 private PermissionSet GetServicePermission(ManagedService svc)
 {
     MyLogger.Trace("Entering {0} for service: {1}", MethodBase.GetCurrentMethod().Name, svc.ConsulServiceName);
     // Creates a permission set that allows no access to the resource.
     PermissionSet ps = new PermissionSet(System.Security.Permissions.PermissionState.None);
     // Sets the security permission flag to use for this permission set.
     ps.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.Assertion));
     // Initializes a new instance of the System.ServiceProcess.ServiceControllerPermission class.
     ps.AddPermission(new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, svc.WindowsServiceName));
     ps.Demand();
     return ps;
 }
        public bool Build(X509Certificate2 certificate)
        {
            if (certificate == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
            if (certificate.Handle == IntPtr.Zero)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("certificate", SR.GetString(SR.ArgumentInvalidCertificate));

            SafeCertChainHandle safeCertChainHandle = SafeCertChainHandle.InvalidHandle;
            X509ChainPolicy chainPolicy = this.ChainPolicy;
            chainPolicy.VerificationTime = DateTime.Now;
            if (chainPolicy.RevocationMode == X509RevocationMode.Online)
            {
                if (certificate.Extensions[CAPI.szOID_CRL_DIST_POINTS] != null ||
                    certificate.Extensions[CAPI.szOID_AUTHORITY_INFO_ACCESS] != null)
                {
                    // If there is a CDP or AIA extension, we demand unrestricted network access and store add permission
                    // since CAPI can download certificates into the CA store from the network.
                    PermissionSet ps = new PermissionSet(PermissionState.None);
                    ps.AddPermission(new WebPermission(PermissionState.Unrestricted));
                    ps.AddPermission(new StorePermission(StorePermissionFlags.AddToStore));
                    ps.Demand();
                }
            }

            BuildChain(this.useMachineContext ? new IntPtr(CAPI.HCCE_LOCAL_MACHINE) : new IntPtr(CAPI.HCCE_CURRENT_USER),
                    certificate.Handle,
                    chainPolicy.ExtraStore,
                    chainPolicy.ApplicationPolicy,
                    chainPolicy.CertificatePolicy,
                    chainPolicy.RevocationMode,
                    chainPolicy.RevocationFlag,
                    chainPolicy.VerificationTime,
                    chainPolicy.UrlRetrievalTimeout,
                    out safeCertChainHandle);

            // Verify the chain using the specified policy.
            CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA)));
            CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS)));

            // Ignore peertrust.  Peer trust caused the chain to succeed out-of-the-box in Vista.
            // This new flag is only available in Vista.
            PolicyPara.dwFlags = (uint)chainPolicy.VerificationFlags | CAPI.CERT_CHAIN_POLICY_IGNORE_PEER_TRUST_FLAG;

            if (!CAPI.CertVerifyCertificateChainPolicy(new IntPtr(this.chainPolicyOID),
                                                       safeCertChainHandle,
                                                       ref PolicyPara,
                                                       ref PolicyStatus))
            {
                int error = Marshal.GetLastWin32Error();
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(error));
            }

            if (PolicyStatus.dwError != CAPI.S_OK)
            {
                int error = (int)PolicyStatus.dwError;
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.X509ChainBuildFail,
                    SecurityUtils.GetCertificateId(certificate), new CryptographicException(error).Message)));
            }

            return true;
        }
示例#13
0
		public void Demand ()
		{
			// check all collection in a single stack walk
			PermissionSet superset = new PermissionSet (PermissionState.None);
			foreach (PermissionSet ps in _list) {
				foreach (IPermission p in ps) {
					superset.AddPermission (p);
				}
			}
			superset.Demand ();
		}
示例#14
0
        // internal - get called by JIT generated code

        private static void InternalDemand(IntPtr permissions, int length)
        {
            PermissionSet ps = Decode(permissions, length);

            ps.Demand();
        }
示例#15
0
		public static void PermissionSetDemo()
		{
			
			Console.WriteLine("Executing Permission Set Demo");
			try
			{
				// Open a permission set.
				PermissionSet ps1 = new PermissionSet(PermissionState.None);
				Console.WriteLine("Adding permission to open a file from a file dialog box.");
				// Add a permission to the permission set.
				ps1.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open));
				Console.WriteLine("Demanding Permission to open a file.");
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				Console.WriteLine("Adding permission to save a file from a file dialog box.");
				ps1.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Save));
				Console.WriteLine("Demanding permission to open and save a file.");
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				Console.WriteLine("Adding a permission to read environment variable USERNAME.");
				ps1.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"));
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				Console.WriteLine("Adding permission to read environment variable COMPUTERNAME.");
				ps1.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "COMPUTERNAME"));
				// Demand all the permissions in the set.
				Console.WriteLine("Demand all permissions.");
				ps1.Demand();
				Console.WriteLine("Demand succeeded.");
				// Display the number of permissions in the set.
				Console.WriteLine("Number of permissions = " + ps1.Count);
				// Display the value of the IsSynchronized property.
				Console.WriteLine("IsSynchronized property = " + ps1.IsSynchronized);
				// Display the value of the IsReadOnly property.
				Console.WriteLine("IsReadOnly property = " + ps1.IsReadOnly);
				// Display the value of the SyncRoot property.
				Console.WriteLine("SyncRoot property = " + ps1.SyncRoot);
				// Display the result of a call to the ContainsNonCodeAccessPermissions method.
				// Gets a value indicating whether the PermissionSet contains permissions
				// that are not derived from CodeAccessPermission.
				// Returns true if the PermissionSet contains permissions that are not 
				// derived from CodeAccessPermission; otherwise, false.
				Console.WriteLine("ContainsNonCodeAccessPermissions method returned " + ps1.ContainsNonCodeAccessPermissions());
				Console.WriteLine("Value of the permission set ToString = \n" + ps1.ToString());
				PermissionSet ps2 = new PermissionSet(PermissionState.None);
				// Create a second permission set and compare it to the first permission set.
				ps2.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME"));
				ps2.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Write, "COMPUTERNAME"));
				Console.WriteLine("Permission set 2 = " + ps2);
				IEnumerator list = ps1.GetEnumerator();
				Console.WriteLine("Permissions in first permission set:");
				foreach (var permission in ps1)
					Console.WriteLine(permission.ToString());
				Console.WriteLine("Second permission IsSubSetOf first permission = " + ps2.IsSubsetOf(ps1));
				// Display the intersection of two permission sets.
				PermissionSet ps3 = ps2.Intersect(ps1);
				Console.WriteLine("The intersection of the first permission set and the second permission set = " + ps3.ToString());
				// Create a new permission set.
				PermissionSet ps4 = new PermissionSet(PermissionState.None);
				ps4.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, "C:\\Temp\\Testfile.txt"));
				ps4.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, "C:\\Temp\\Testfile.txt"));
				// Display the union of two permission sets.
				PermissionSet ps5 = ps3.Union(ps4);
				Console.WriteLine("The union of permission set 3 and permission set 4 = " + ps5.ToString());
				// Remove FileIOPermission from the permission set.
				ps5.RemovePermission(typeof(FileIOPermission));
				Console.WriteLine("The last permission set after removing FileIOPermission = " + ps5.ToString());
				// Change the permission set using SetPermission
				ps5.SetPermission(new EnvironmentPermission(EnvironmentPermissionAccess.AllAccess, "USERNAME"));
				Console.WriteLine("Permission set after SetPermission = " + ps5.ToString());
				// Display result of ToXml and FromXml operations.
				PermissionSet ps6 = new PermissionSet(PermissionState.None);
				ps6.FromXml(ps5.ToXml());
				Console.WriteLine("Result of ToFromXml = " + ps6.ToString() + "\n");
				// Display result of PermissionSet.GetEnumerator.
				IEnumerator psEnumerator = ps1.GetEnumerator();
				while (psEnumerator.MoveNext())
				{
					Console.WriteLine(psEnumerator.Current.ToString());
				}
				// Check for an unrestricted permission set.
				PermissionSet ps7 = new PermissionSet(PermissionState.Unrestricted);
				Console.WriteLine("Permission set is unrestricted = " + ps7.IsUnrestricted());
				// Create and display a copy of a permission set.
				ps7 = ps5.Copy();
				Console.WriteLine("Result of copy = " + ps7.ToString());
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message.ToString());
			}
		}
示例#16
0
        /// <summary>
        /// The main.
        /// </summary>
        private void main()
        {
            Console.WriteLine("=======ClueBuddy=======");
            try {
                var savingPermissions = new PermissionSet(null);
                savingPermissions.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Save));
                savingPermissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                savingPermissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));

                // briefly demand these permissions to detect whether we'll succeed later
                savingPermissions.Demand();
            } catch (SecurityException) {
                ConsoleHelper.WriteColor(ConsoleColor.Red, "WARNING: insufficient permissions to save games.");
            }
            while (true) {
                try {
                    if (this.game != null && this.game.AreCluesConflicted) {
                        this.ResolveConflicts();
                    }

                    var mainMenu = new Dictionary<char, string>();
                    mainMenu.Add('L', "Load game");
                    mainMenu.Add('N', "New game");
                    if (this.game != null) {
                        mainMenu.Add('S', "Save game");
                        mainMenu.Add('T', "Play a Turn");
                        mainMenu.Add('G', "See Grid");
                        mainMenu.Add('C', "List Clues");
                        mainMenu.Add('F', "Force enter a clue");
                    }
                    mainMenu.Add('Q', "Quit");
                    switch (ConsoleHelper.Choose("Main menu:", mainMenu, s => s).Key) {
                        case 'L':
                            this.LoadGame();
                            break;
                        case 'N':
                            this.ChooseGame();
                            if (this.game == null) break;
                            this.SetupPlayers();
                            this.game.Start();
                            this.prepareNewOrLoadedGameState();
                            this.LearnOwnHand();
                            break;
                        case 'S':
                            this.SaveGame();
                            break;
                        case 'T':
                            this.TakeTurn();
                            break;
                        case 'F':
                            this.ForceClue();
                            break;
                        case 'G':
                            this.PrintGrid();
                            break;
                        case 'C':
                            this.ListClues();
                            break;
                        case 'Q':
                            return;
                    }
                } catch (SecurityException ex) {
                    Console.Error.WriteLine("Insufficient permissions: {0}.", ex.Demanded);
                } catch (Exception e) {
                    if (e is OutOfMemoryException || e is StackOverflowException) throw;
                    if (ConsoleHelper.Choose(string.Format("An {0} exception was thrown: {1}.{2}Do you want to try to continue the game?",
                        e.GetType().Name, e.Message, Environment.NewLine), false, new[] { "Yes", "No" }) == 1)
                        throw;
                }
            }
        }
示例#17
0
 public static void Log3(string text)
 {
     PermissionSet p = new PermissionSet(PermissionState.Unrestricted);
     p.Demand();
 }
示例#18
0
		/// <summary>
		/// Check security permissions
		/// </summary>
		public static bool CheckSecurity()
		{
			try
			{
				PermissionSet set = new PermissionSet(PermissionState.Unrestricted);
				set.Demand();
			}
			catch
			{
				return false;
			}
			return true;
		}
示例#19
0
            private static void SendKeyboardInput(Key key, bool press)
            {
                PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);
                permissions.Demand();

                NativeMethods.INPUT ki = new NativeMethods.INPUT();
                ki.type = NativeMethods.InputKeyboard;
                ki.union.keyboardInput.wVk = (short)KeyInterop.VirtualKeyFromKey(key);
                ki.union.keyboardInput.wScan = (short)NativeMethods.MapVirtualKey(ki.union.keyboardInput.wVk, 0);

                int dwFlags = 0;

                if (ki.union.keyboardInput.wScan > 0)
                {
                    dwFlags |= NativeMethods.KeyeventfScancode;
                }

                if (!press)
                {
                    dwFlags |= NativeMethods.KeyeventfKeyup;
                }

                ki.union.keyboardInput.dwFlags = dwFlags;

                ki.union.keyboardInput.time = 0;
                ki.union.keyboardInput.dwExtraInfo = new IntPtr(0);

                if (NativeMethods.SendInput(1, ref ki, Marshal.SizeOf(ki)) == 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
示例#20
0
        /// <summary>
        /// Initializes the permissions manager with the permissions required by an install script.
        /// </summary>
        internal static void Init()
        {
            #if TRACE
            Trace.WriteLine("");
            Trace.WriteLine("Setting up File IO Permissions for: ");
            Trace.Indent();
            Trace.Write("     FOMM tmp Dir: ");
            Trace.WriteLine(Program.tmpPath);
            Trace.Write(" Install Info Dir: ");
            Trace.WriteLine(Program.GameMode.InstallInfoDirectory);
            Trace.Write("   System tmp Dir: ");
            Trace.WriteLine(Path.GetTempPath());
            Directory.GetAccessControl(Path.GetTempPath());
            Trace.WriteLine("   Settings Files: ");
            Trace.Indent();
            foreach (string strValue in Program.GameMode.SettingsFiles.Values)
                Trace.WriteLine(strValue);
            Trace.Unindent();
            Trace.WriteLine("      Other Paths: ");
            Trace.Indent();
            foreach (string strValue in Program.GameMode.AdditionalPaths.Values)
                Trace.WriteLine(strValue);
            Trace.Unindent();
            Trace.Unindent();
            Trace.Flush();
            #endif
            permissions = new PermissionSet(PermissionState.None);
            //do the following paths need to add to this?
            // savesPath - fallout 3
            FileIOPermission fipFilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new string[] {
                Program.tmpPath, Path.GetTempPath(),
                Program.GameMode.InstallInfoDirectory,
                Program.GameMode.PluginsPath
            });

            List<string> lstPaths = new List<string>(Program.GameMode.SettingsFiles.Values);
            lstPaths.AddRange(Program.GameMode.AdditionalPaths.Values);
            fipFilePermission.AddPathList(FileIOPermissionAccess.AllAccess, lstPaths.ToArray());
            fipFilePermission.AddPathList(FileIOPermissionAccess.Read, Environment.CurrentDirectory);

            permissions.AddPermission(fipFilePermission);
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            permissions.AddPermission(new UIPermission(UIPermissionWindow.AllWindows));
            #if TRACE
            Trace.Write("Demanding access to System tmp Dir...");
            try
            {
                permissions.Demand();
                Trace.WriteLine("Succeeded.");
            }
            catch (Exception e)
            {
                Trace.WriteLine("Failed:");
                Program.TraceException(e);
            }
            Trace.WriteLine("   System tmp Dir Permissions:");
            Trace.Indent();
            DirectorySecurity drsPermissions = Directory.GetAccessControl(Path.GetTempPath());
            Dictionary<string, List<FileSystemRights>> dicRights = new Dictionary<string, List<FileSystemRights>>();
            foreach (FileSystemAccessRule fsrRule in drsPermissions.GetAccessRules(true, true, typeof(NTAccount)))
            {
                if (!dicRights.ContainsKey(fsrRule.IdentityReference.Value))
                    dicRights[fsrRule.IdentityReference.Value] = new List<FileSystemRights>();
                dicRights[fsrRule.IdentityReference.Value].Add(fsrRule.FileSystemRights);
            }
            foreach (KeyValuePair<string, List<FileSystemRights>> kvpRight in dicRights)
            {
                Trace.WriteLine(kvpRight.Key + " =>");
                Trace.Indent();
                foreach (FileSystemRights fsrRight in kvpRight.Value)
                    Trace.WriteLine(fsrRight.ToString());
                Trace.Unindent();
            }
            Trace.Unindent();
            Trace.Write("Testing access to System tmp Dir...");
            try
            {
                File.WriteAllText(Path.Combine(Path.GetTempPath(), "testFile.txt"), "This is fun.");
                Trace.WriteLine("Passed: " + File.ReadAllText(Path.Combine(Path.GetTempPath(), "testFile.txt")));
                File.Delete(Path.Combine(Path.GetTempPath(), "testFile.txt"));
            }
            catch (Exception e)
            {
                Trace.WriteLine("Failed: ");
                Program.TraceException(e);
            }
            #endif
        }
        private static void SendMouseInput(int x, int y, int data, NativeMethods.SendMouseInputFlags flags, bool delay = true) {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);
            permissions.Demand();

            int intflags = (int)flags;

            if ((intflags & (int)NativeMethods.SendMouseInputFlags.Absolute) != 0) {
                // Absolute position requires normalized coordinates.
                NormalizeCoordinates(ref x, ref y);
                intflags |= NativeMethods.MouseeventfVirtualdesk;
            }

            NativeMethods.INPUT mi = new NativeMethods.INPUT();
            mi.type = NativeMethods.InputMouse;
            mi.union.mouseInput.dx = x;
            mi.union.mouseInput.dy = y;
            mi.union.mouseInput.mouseData = data;
            mi.union.mouseInput.dwFlags = intflags;
            mi.union.mouseInput.time = 0;
            mi.union.mouseInput.dwExtraInfo = new IntPtr(0);

            if (NativeMethods.SendInput(1, ref mi, Marshal.SizeOf(mi)) == 0) {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            if (delay) {
                System.Threading.Thread.Sleep(250);
            }
        }
 public int Fill(DataTable dataTable, object ADODBRecordSet)
 {
     int num;
     IntPtr ptr;
     PermissionSet set = new PermissionSet(PermissionState.None);
     set.AddPermission(OleDbConnection.ExecutePermission);
     set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
     set.Demand();
     Bid.ScopeEnter(out ptr, "<oledb.OleDbDataAdapter.Fill|API> %d#, dataTable, ADODBRecordSet\n", base.ObjectID);
     try
     {
         if (dataTable == null)
         {
             throw ADP.ArgumentNull("dataTable");
         }
         if (ADODBRecordSet == null)
         {
             throw ADP.ArgumentNull("adodb");
         }
         num = this.FillFromADODB(dataTable, ADODBRecordSet, null, false);
     }
     finally
     {
         Bid.ScopeLeave(ref ptr);
     }
     return num;
 }
        private static void SendKeyboardInput(Key key, bool press) {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);
            permissions.Demand();

            NativeMethods.INPUT ki = new NativeMethods.INPUT();
            ki.type = NativeMethods.InputKeyboard;
            ki.union.keyboardInput.wVk = (short)KeyInterop.VirtualKeyFromKey(key);
            ki.union.keyboardInput.wScan = (short)NativeMethods.MapVirtualKey(ki.union.keyboardInput.wVk, 0);
            int dwFlags = 0;
            if (ki.union.keyboardInput.wScan > 0) {
                dwFlags |= NativeMethods.KeyeventfScancode;
            }
            if (!press) {
                dwFlags |= NativeMethods.KeyeventfKeyup;
            }
            ki.union.keyboardInput.dwFlags = dwFlags;
            if (ExtendedKeys.Contains(key)) {
                ki.union.keyboardInput.dwFlags |= NativeMethods.KeyeventfExtendedkey;
            }
            ki.union.keyboardInput.time = 0;
            ki.union.keyboardInput.dwExtraInfo = new IntPtr(0);
            if (NativeMethods.SendInput(1, ref ki, Marshal.SizeOf(ki)) == 0) {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            //Pause briefly to ensure the keyboard event was processed
            System.Threading.Thread.Sleep(10);
        }
            static void PromoteTransaction(Transaction transactionToPromote)
            {
                // TransactionInterop.GetDtcTransaction has a link demand for full trust. If we are not running in full trust, don't make the call.
                // If we are running in full trust, it is possible that we got invoked thru a cross AppDomain call from a partially trusted
                // AppDomain. So extend the demand for full trust to a full demand.
                if ((PartialTrustHelpers.AppDomainFullyTrusted) && (transactionToPromote != null))
                {
                    PermissionSet ps = new PermissionSet(PermissionState.Unrestricted);
                    ps.Demand();

                    TransactionInterop.GetDtcTransaction(transactionToPromote);
                }
            }
        public int Fill(DataSet dataSet, object ADODBRecordSet, string srcTable) {
            System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
            permissionSet.AddPermission(OleDbConnection.ExecutePermission); // MDAC 77737
            permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode));
            permissionSet.Demand();

            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<oledb.OleDbDataAdapter.Fill|API> %d#, dataSet, ADODBRecordSet, srcTable='%ls'\n", ObjectID, srcTable);
            try {
                if (null == dataSet) {
                    throw ADP.ArgumentNull("dataSet");
                }
                if (null == ADODBRecordSet) {
                    throw ADP.ArgumentNull("adodb");
                }
                if (ADP.IsEmpty(srcTable)) {
                    throw ADP.FillRequiresSourceTableName("srcTable");
                }
                // user was required to have UnmanagedCode Permission just to create ADODB
                // (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand();
                return FillFromADODB((object)dataSet, ADODBRecordSet, srcTable, true);
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }
示例#26
0
        private static void PerformMouseAction(int coord_x, int coord_y, int something, MouseInputFlags flags)
        {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);
            permissions.Demand();

            int intflags = (int)flags;

            if ((intflags & (int)MouseInputFlags.Absolute) != 0)
            {
                // Absolute position requires normalized coordinates.
                NormalizeCoordinates(ref coord_x, ref coord_y);
                intflags |= MouseeventfVirtualdesk;
            }

            INPUT mi = new INPUT();
            mi.type = InputMouse;
            mi.union.mouseInput.dx = coord_x;
            mi.union.mouseInput.dy = coord_y;
            mi.union.mouseInput.mouseData = something;
            mi.union.mouseInput.dwFlags = intflags;
            mi.union.mouseInput.time = 0;
            mi.union.mouseInput.dwExtraInfo = new IntPtr(0);

            if (SendInput(1, ref mi, Marshal.SizeOf(mi)) == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
 private void EnlistDistributedTransactionHelper(ITransaction transaction)
 {
     PermissionSet set = new PermissionSet(PermissionState.None);
     set.AddPermission(ExecutePermission);
     set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
     set.Demand();
     Bid.Trace("<prov.DbConnectionHelper.EnlistDistributedTransactionHelper|RES|TRAN> %d#, Connection enlisting in a transaction.\n", this.ObjectID);
     System.Transactions.Transaction transactionFromDtcTransaction = null;
     if (transaction != null)
     {
         transactionFromDtcTransaction = TransactionInterop.GetTransactionFromDtcTransaction((IDtcTransaction) transaction);
     }
     this.InnerConnection.EnlistTransaction(transactionFromDtcTransaction);
     GC.KeepAlive(this);
 }
 partial void AssertPermissions()
 {
   // Security Asserts can only be done when the assemblies 
   // are put in the GAC as documented in 
   // http://msdn.microsoft.com/en-us/library/ff648665.aspx
   if (this.Settings.IncludeSecurityAsserts)
   {
     PermissionSet set = new PermissionSet(PermissionState.None);
     set.AddPermission(new MySqlClientPermission(ConnectionString));
     set.Demand();
     MySqlSecurityPermission.CreatePermissionSet(true).Assert(); 
   }
 }
示例#29
0
        private static void InternalDemand(IntPtr permissions, int length)
        {
            PermissionSet permissionSet = SecurityManager.Decode(permissions, length);

            permissionSet.Demand();
        }
示例#30
0
        /// <summary>
        /// Creates a new app domain for plugins.
        /// </summary>
        /// <param name="pluginpath">The path to where plugins will be loaded from.</param>
        private static AppDomain CreatePluginDomain(string pluginpath)
        {
            // Setup plugin permissions
            PermissionSet permissions = new PermissionSet(PermissionState.None);
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Infrastructure | SecurityPermissionFlag.RemotingConfiguration));
            //permissions.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new UIPermission(UIPermissionWindow.AllWindows));
            permissions.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new SocketPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new WebPermission(PermissionState.Unrestricted));
            permissions.Demand();

            // Get the strong name for the deployer assembly so it can be fully trusted in the new domain.
            StrongName deployerEngineStrongName = GetStrongName(Assembly.GetExecutingAssembly());

            // Create new appdomain with the specified permission set
            AppDomainSetup domaininfo = new AppDomainSetup();
            domaininfo.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            domaininfo.PrivateBinPath = pluginpath;
            AppDomain appdomain = AppDomain.CreateDomain("Plugins", AppDomain.CurrentDomain.Evidence, domaininfo, permissions, deployerEngineStrongName);

            return appdomain;
        }