Example #1
0
    //</Snippet7>

    public static void PermitOnlyTestMethod()
    {
        Console.WriteLine("Executing PermitOnlyTestMethod.");
        try
        {
            PermissionSet ps = new PermissionSet(PermissionState.None);
            ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write,
                                                  "C:\\Documents and Settings\\All Users\\Application Data\\Microsoft\\Network\\SomeFile"));
            Console.WriteLine("Demanding permission to write " +
                              "'C:\\Documents and Settings\\All Users\\Application Data\\Microsoft\\Network\\SomeFile'");
            ps.Demand();
            Console.WriteLine("Demand succeeded.");
            ps.AddPermission(
                new FileIOPermission(FileIOPermissionAccess.Write,
                                     "C:\\"));
            Console.WriteLine("Demanding permission to write to drive C.");

            // This demand should cause an exception.
            ps.Demand();
            // The TestFailed method is called if an exception is not thrown.
            TestFailed();
        }
        catch (Exception e)
        {
            Console.WriteLine("An exception was thrown because of a write demand: " + e.Message);
        }
    }
        internal static void DemandClientConnectionPermissions(ServiceEndpoint endpoint)
        {
            PermissionSet connectionSet = new PermissionSet(PermissionState.None);

            if (endpoint.Binding is NetTcpBinding)
            {
                connectionSet.AddPermission(new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, endpoint.Address.Uri.Host, endpoint.Address.Uri.Port));
                connectionSet.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            }
            if (endpoint.Binding is WebHttpBinding || endpoint.Binding is WSHttpBinding || endpoint.Binding is BasicHttpBinding || endpoint.Binding is WSDualHttpBinding)
            {
                connectionSet.AddPermission(new WebPermission(NetworkAccess.Connect, endpoint.Address.Uri.AbsoluteUri));
            }
            //On the client, demand hosting permission for duplex over HTTP
            if (endpoint.Binding is WSDualHttpBinding)
            {
                connectionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));

                WSDualHttpBinding binding = endpoint.Binding as WSDualHttpBinding;

                Uri callbackUri = binding.ClientBaseAddress ?? new Uri("http://localhost:80/");

                connectionSet.AddPermission(new WebPermission(NetworkAccess.Accept, callbackUri.AbsoluteUri));
            }
            if (endpoint.Binding is NetMsmqBinding)
            {
                string path = QueuedServiceHelper.GetQueueFromUri(endpoint.Address.Uri);
                connectionSet.AddPermission(new MessageQueuePermission(MessageQueuePermissionAccess.Send, path));
            }
            connectionSet.Demand();
        }
Example #3
0
        private static void SendMouseInput(int x, int y, int data, SendMouseInputFlags flags)
        {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);

            permissions.Demand();

            uint intflags = (uint)flags;

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

            INPUT mouseInput = new INPUT();

            mouseInput.Type                   = NativeMethods.INPUT_MOUSE;
            mouseInput.Data.Mouse.dx          = x;
            mouseInput.Data.Mouse.dy          = y;
            mouseInput.Data.Mouse.mouseData   = data;
            mouseInput.Data.Mouse.dwFlags     = intflags;
            mouseInput.Data.Mouse.time        = 0;
            mouseInput.Data.Mouse.dwExtraInfo = new IntPtr(0);

            if (NativeMethods.SendInput(1, new INPUT[] { mouseInput }, Marshal.SizeOf(mouseInput)) == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
        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);
        }
        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);
        }
Example #6
0
        private static void DemandGrantSet(Assembly assembly)
        {
            PermissionSet targetGrantSet = new PermissionSet(PermissionState.None); //assembly.PermissionSet;

            targetGrantSet.AddPermission(RestrictedMemberAccessPermission);
            targetGrantSet.Demand();
        }
        public DynamicBuildPlanGenerationContext(Type typeToBuild)
        {
            Guard.ArgumentNotNull(typeToBuild, "typeToBuild");
            this.typeToBuild = typeToBuild;

            // Check for full trust. We can't add the method to the
            // built up type without it.

            try
            {
                PermissionSet fullTrust = new PermissionSet(PermissionState.Unrestricted);
                fullTrust.Demand();

                if (typeToBuild.IsInterface)
                {
                    CreateMethodOnModule(typeToBuild.Module);
                }
                else
                {
                    CreateMethodOnBuiltUpType();
                }
            }
            catch (SecurityException)
            {
                // Not in full trust, add IL to this module instead.
                CreateMethodOnModule(GetType().Module);
            }

            il = buildMethod.GetILGenerator();
            CreatePreamble();
        }
Example #8
0
        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);
            }
        }
Example #9
0
        public static void WaitFor(DispatcherPriority priority)
        {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);

            permissions.Demand();
            WaitFor(TimeSpan.Zero, priority);
        }
Example #10
0
        private static void DemandGrantSet(Assembly assembly)
        {
            PermissionSet permissionSet = assembly.PermissionSet;

            permissionSet.AddPermission(RestrictedMemberAccessPermission);
            permissionSet.Demand();
        }
Example #11
0
        public static void WaitFor(TimeSpan time)
        {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);

            permissions.Demand();
            WaitFor(time, DispatcherPriority.SystemIdle);
        }
Example #12
0
        public static void EnableIfDisabled(String serviceName)
        {
            try
            {
                var fullTrust = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
                fullTrust.Demand();
                using (var service = new ManagementObject(string.Format("Win32_Service.Name=\"{0}\"", serviceName)))

                /*
                 * string wmiQuery = @"SELECT * FROM Win32_Service WHERE Name='" + serviceName + @"'";
                 * var searcher = new ManagementObjectSearcher(wmiQuery);
                 * ManagementObjectCollection results = searcher.Get();
                 * foreach (ManagementObject service in results)*/
                {
                    if (service["StartMode"].ToString() == "Disabled" || service["StartMode"].ToString() == "Manual")
                    {
                        Console.WriteLine("Enabling " + ServiceName + ".");
                        service.InvokeMethod("ChangeStartMode", new object[] { "Automatic" });
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to check if service was enabled or enable it.");
            }
        }
Example #13
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());
            }
        }
        public StartupState GetServiceState(string serviceName)
        {
            StartupState state = StartupState.Automatic;

            try
            {
                PermissionSet fullTrust = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
                fullTrust.Demand();
                string wmiQuery = $"SELECT * FROM Win32_Service WHERE Name='{serviceName}'";
                ManagementObjectSearcher   searcher = new ManagementObjectSearcher(wmiQuery);
                ManagementObjectCollection results  = searcher.Get();
                foreach (var service in results)
                {
                    if (service["StartMode"].ToString() == "Disabled")
                    {
                        state = StartupState.Disabled;
                    }
                    else
                    {
                        state = StartupState.Enabled;
                    }
                }
                return(state);
            }
            catch (SecurityException se)
            {
                return(StartupState.Refused);
            }
            catch (Exception e)
            {
                return(StartupState.Error);
            }
        }
Example #15
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;
            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());
            }
        }
Example #16
0
        private static void SendKeyboardInput(Keys key, bool press)
        {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);

            permissions.Demand();

            short wVk     = (short)key;
            short wScan   = (short)MapVirtualKey(wVk, 0);
            int   dwFlags = 0;

            if (wScan > 0)
            {
                dwFlags |= 0x0008; // KeyeventfScancode
            }
            if (!press)
            {
                dwFlags |= 0x0002; // KeyeventfKeyup
            }
            var input = new INPUT()
            {
                Type          = 1,
                KeyboardInput = new KEYBDINPUT()
                {
                    wVk         = wVk,
                    wScan       = wScan,
                    dwFlags     = dwFlags,
                    time        = 0,
                    dwExtraInfo = new IntPtr(0)
                }
            };

            SendInput(1, ref input, Marshal.SizeOf(input));
        }
Example #17
0
        private static void SendMouseInput(int x, int y, int data, SendMouseInputFlags flags)
        {
            var permissions = new PermissionSet(PermissionState.Unrestricted);

            permissions.Demand();
            int dX = x, dY = y;

            if (((int)flags & (int)SendMouseInputFlags.Absolute) != 0)
            {
                int vScreenWidth  = GetSystemMetrics(78); // SMCxvirtualscreen
                int vScreenHeight = GetSystemMetrics(79); // SMCyvirtualscreen
                int vScreenLeft   = GetSystemMetrics(76); // SMXvirtualscreen
                int vScreenTop    = GetSystemMetrics(77); // SMYvirtualscreen
                dX = (x - vScreenLeft) * 65536 / vScreenWidth + 65536 / (vScreenWidth * 2);
                dY = (y - vScreenTop) * 65536 / vScreenHeight + 65536 / (vScreenHeight * 2);
            }
            var input = new INPUT()
            {
                Type       = 0,
                MouseInput = new MOUSEINPUT()
                {
                    dX          = dX,
                    dY          = dY,
                    mouseData   = data,
                    dwFlags     = (int)flags,
                    time        = 0,
                    dwExtraInfo = new IntPtr(0)
                }
            };

            SendInput(1, ref input, Marshal.SizeOf(input));
        }
Example #18
0
        private static void SendMouseInput(int x, int y, int data, MySendKeys.SendMouseInputFlags flags)
        {
            PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);

            permissions.Demand();

            int intflags = (int)flags;

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

            MySendKeys.INPUT mi = new MySendKeys.INPUT();
            mi.type = MySendKeys.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 (MySendKeys.SendInput(1, ref mi, Marshal.SizeOf(mi)) == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
 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);
     }
 }
        public static void ImperativeCAS()
        {
            PermissionSet perms = new PermissionSet(PermissionState.None);

            perms.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, @"C:\Windows"));
            perms.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, @"C:\Inetpub"));
            perms.AddPermission(new RegistryPermission(RegistryPermissionAccess.Write, @"HKEY_LOCAL_MACHINE\Software"));

            FileIOPermission myFilePermissions = new FileIOPermission(FileIOPermissionAccess.Write, @"C:\Program Files\");

            FileIOPermission f = new FileIOPermission(PermissionState.None);

            f.AllLocalFiles = FileIOPermissionAccess.Read;
            try
            {
                Console.WriteLine("ImperativeCAS");
                f.Demand();

                perms.Demand();
                myFilePermissions.Demand();
                f.Demand();
            }
            catch (SecurityException s)
            {
                Console.WriteLine(s.Message);
            }
        }
Example #21
0
        public virtual Type GetScriptClass(string code, string classSuffix, XPathNavigator scriptNode, Evidence evidence)
        {
            PermissionSet ps = SecurityManager.ResolvePolicy(evidence);

            if (ps != null)
            {
                ps.Demand();
            }

            ICodeCompiler      compiler   = CodeDomProvider.CreateCompiler();
            CompilerParameters parameters = new CompilerParameters();

            parameters.CompilerOptions = DefaultCompilerOptions;

            // get source filename
            string filename = String.Empty;

            try {
                if (scriptNode.BaseURI != String.Empty)
                {
                    filename = new Uri(scriptNode.BaseURI).LocalPath;
                }
            } catch (FormatException) {
            }
            if (filename == String.Empty)
            {
                filename = "__baseURI_not_supplied__";
            }

            // get source location
            IXmlLineInfo li = scriptNode as IXmlLineInfo;

            string source = SourceTemplate.Replace("{0}",
                                                   DateTime.Now.ToString(CultureInfo.InvariantCulture))
                            .Replace("{1}", classSuffix)
                            .Replace("{2}", code);

            source = FormatSource(li, filename, source);

            CompilerResults res = compiler.CompileAssemblyFromSource(parameters, source);

            foreach (CompilerError err in res.Errors)
            {
                if (!err.IsWarning)
                {
                    // Actually it should be
                    // XsltCompileException, but to match
                    // with silly MS implementation...
//					throw new XsltCompileException ("Stylesheet script compile error: \n" + FormatErrorMessage (res) /*+ "Code :\n" + source*/, null, scriptNode);
                    throw new XsltException("Stylesheet script compile error: \n" + FormatErrorMessage(res) /*+ "Code :\n" + source*/, null, scriptNode);
                }
            }

            if (res.CompiledAssembly == null)
            {
                throw new XsltCompileException("Cannot compile stylesheet script", null, scriptNode);
            }
            return(res.CompiledAssembly.GetType("GeneratedAssembly.Script" + classSuffix));
        }
Example #22
0
 internal static void DemandPlugInSerializerPermissions()
 {
     if (_plugInSerializerPermissions == null)
     {
         _plugInSerializerPermissions = new PermissionSet(PermissionState.Unrestricted);
     }
     _plugInSerializerPermissions.Demand();
 }
 internal void DemandPermission()
 {
     if (_permissionset is null)
     {
         _permissionset = CreatePermissionSet();
     }
     _permissionset.Demand();
 }
Example #24
0
        private static void DemandGrantSet(Assembly assembly)
        {
#if MONO_FEATURE_CAS
            PermissionSet targetGrantSet = assembly.PermissionSet;
            targetGrantSet.AddPermission(RestrictedMemberAccessPermission);
            targetGrantSet.Demand();
#endif
        }
Example #25
0
        private static void DemandGrantSet(Assembly assembly)
        {
            // TODO .netCore中不再支持get_PermissionSet属性
            // PermissionSet targetGrantSet = assembly.PermissionSet;
            PermissionSet targetGrantSet = new PermissionSet(PermissionState.None);

            targetGrantSet.AddPermission(RestrictedMemberAccessPermission);
            targetGrantSet.Demand();
        }
        private static void DemandRestrictedMemberAccess(MemberInfo target)
        {
            Assembly targetAssembly = target.Assembly();

            PermissionSet targetGrantSet = UnsafePermissionSet(targetAssembly);

            targetGrantSet.AddPermission(_restrictedMemberAccess);
            targetGrantSet.Demand();
        }
Example #27
0
 private void AssertPermissions()
 {
     if (this.Settings.IncludeSecurityAsserts)
     {
         PermissionSet permissionSet = new PermissionSet(PermissionState.None);
         permissionSet.AddPermission(new MySqlClientPermission(this.ConnectionString));
         permissionSet.Demand();
         MySqlSecurityPermission.CreatePermissionSet(true).Assert();
     }
 }
Example #28
0
 internal void FailoverPermissionDemand()
 {
     if (this._useFailoverPartner)
     {
         PermissionSet set = this._failoverPermissionSet;
         if (set != null)
         {
             set.Demand();
         }
     }
 }
 void UnsupportedSecurityCheck(string resource, Type type)
 {
     try
     {
         fullTrust.Demand();
     }
     catch (SecurityException)
     {
         throw new InvalidOperationException(SR.GetString(resource, binding.Name, type));
     }
 }
 private void UnsupportedSecurityCheck(string resource, System.Type type)
 {
     try
     {
         fullTrust.Demand();
     }
     catch (SecurityException)
     {
         throw new InvalidOperationException(System.ServiceModel.SR.GetString(resource, new object[] { this.binding.Name, type }));
     }
 }
Example #31
0
    public static void Main(string[] args)
    {
        try
        {
            // Create a new, empty permission set so we don't mistakenly grant some permission we don't want
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);
            // Set the permissions that you will allow, in this case we only want to allow execution of code
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            // Make sure we have the permissions currently
            permissionSet.Demand();

            // Create the security policy level for this application domain
            PolicyLevel policyLevel = PolicyLevel.CreateAppDomainLevel();
            // Give the policy level's root code group a new policy statement based on the new permission set.
            policyLevel.RootCodeGroup.PolicyStatement = new PolicyStatement(permissionSet);

            CSScript.GlobalSettings.AddSearchDir(Environment.CurrentDirectory);

            File.Copy("Danger.cs", "Danger1.cs", true);
            var script = new AsmHelper(CSScript.Load("Danger.cs"));

            // Update the application domain's policy now
            AppDomain.CurrentDomain.SetAppDomainPolicy(policyLevel);

            var script1 = new AsmHelper(CSScript.Load("Danger1.cs"));

            Console.WriteLine();
            Console.WriteLine("Access local file from host application assembly...");
            using (FileStream f = File.Open("somefile.txt", FileMode.OpenOrCreate)) //OK because executing assembly was loaded before the new policy set
                Console.WriteLine("  Ok");
            Console.WriteLine();

            Console.WriteLine("Access local file from Script assembly (before security policy set)...");
            script.Invoke("*.SayHello"); //OK because executing assembly was loaded before the new policy set
            Console.WriteLine();

            Console.WriteLine("Access local file from Script assembly (after security policy set)...\n");
            script1.Invoke("*.SayHello"); //ERROR because executing assembly was loaded after the new policy set

            Console.WriteLine("The end...");
        }
        catch (Exception e)
        {
            Console.WriteLine();
            Console.WriteLine(e.Message);
            Console.WriteLine();
        }
    }
Example #32
0
 public static void PermissionSetCallMethods()
 {
     PermissionSet ps = new PermissionSet(new PermissionState());
     ps.Assert();
     bool containspermissions = ps.ContainsNonCodeAccessPermissions();
     PermissionSet ps2 = ps.Copy();
     ps.CopyTo(new int[1], 0);
     ps.Demand();
     ps.Equals(ps2);
     System.Collections.IEnumerator ie = ps.GetEnumerator();
     int hash = ps.GetHashCode();
     PermissionSet ps3 = ps.Intersect(ps2);
     bool isempty = ps.IsEmpty();
     bool issubsetof = ps.IsSubsetOf(ps2);
     bool isunrestricted = ps.IsUnrestricted();
     string s = ps.ToString();
     PermissionSet ps4 = ps.Union(ps2);
     SecurityElement se = new SecurityElement("");
     ps.FromXml(se);
     se = ps.ToXml();
 }
Example #33
0
    private static void SendMouseInput (int x, int y, int data, NativeMethods.SendMouseInputFlags flags) {
        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 ());
        }
    }
Example #34
0
        public bool Build (X509Certificate2 certificate) {
            lock (m_syncRoot) {
                if (certificate == null || certificate.CertContext.IsInvalid)
                    throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "certificate");

                // Chain building opens and enumerates the root store to see if the root of the chain is trusted.
                StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore | StorePermissionFlags.EnumerateCertificates);
                sp.Demand();

                X509ChainPolicy chainPolicy = this.ChainPolicy;
                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();
                    }
                }

                Reset();
                int hr = BuildChain(m_useMachineContext ? new IntPtr(CAPI.HCCE_LOCAL_MACHINE) : new IntPtr(CAPI.HCCE_CURRENT_USER),
                                    certificate.CertContext,
                                    chainPolicy.ExtraStore,
                                    chainPolicy.ApplicationPolicy,
                                    chainPolicy.CertificatePolicy,
                                    chainPolicy.RevocationMode,
                                    chainPolicy.RevocationFlag,
                                    chainPolicy.VerificationTime,
                                    chainPolicy.UrlRetrievalTimeout,
                                    ref m_safeCertChainHandle);

                if (hr != CAPI.S_OK)
                    return false;

                // Init.
                Init();

                // 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)));

                PolicyPara.dwFlags = (uint) chainPolicy.VerificationFlags;

                if (!CAPI.CertVerifyCertificateChainPolicy(new IntPtr(CAPI.CERT_CHAIN_POLICY_BASE),
                                                           m_safeCertChainHandle,
                                                           ref PolicyPara,
                                                           ref PolicyStatus))
                    // The API failed.
                    throw new CryptographicException(Marshal.GetLastWin32Error());

                CAPI.SetLastError(PolicyStatus.dwError);
                return (PolicyStatus.dwError == 0);
            }
        }
Example #35
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;

        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 ());
        }
    }