Пример #1
0
        private static string GetSystemSound(string soundName)
        {
            string        path = null;
            string        name = InvariantString.Format(@"AppEvents\Schemes\Apps\.Default\{0}\.current\", soundName);
            PermissionSet set  = new PermissionSet(null);

            set.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_CURRENT_USER\AppEvents\Schemes\Apps\.Default\"));
            set.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            set.Assert();
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(name))
                {
                    if (key != null)
                    {
                        path = (string)key.GetValue("");
                    }
                    return(path);
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
Пример #2
0
        GetImageMimeType(
            BitmapEncoder encoder
            )
        {
            string mimetypes;
            string imageMimeType = "image/unknown";
            //
            // To determine the mime-type of the image we just grab
            // the first one supported by this encoder and use that.
            //
            PermissionSet permissions = new PermissionSet(null);

            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            permissions.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
            permissions.Assert();
            try
            {
                mimetypes = encoder.CodecInfo.MimeTypes;
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            int comma = mimetypes.IndexOf(',');

            if (comma != -1)
            {
                imageMimeType = mimetypes.Substring(0, comma);
            }
            else
            {
                imageMimeType = mimetypes;
            }
            return(imageMimeType);
        }
Пример #3
0
        public static List <Byte[]> GetInspectionImages(string inspectionid, string bizServer, string userId, string password)
        {
            PermissionSet ps = new PermissionSet(PermissionState.None);

            ps.AddPermission(new WebPermission(PermissionState.Unrestricted));
            ps.AddPermission(new WebPermission(NetworkAccess.Accept, bizServer));
            ps.AddPermission(new WebPermission(NetworkAccess.Connect, bizServer));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Execution));
            ps.Assert();

            var token = Authenticate(inspectionid, bizServer, userId, password);

            List <Documents> resultList = GetInspectionDocuments(bizServer, inspectionid, token);
            List <Byte[]>    imgByteArr = new List <Byte[]>();

            if (resultList != null)
            {
                foreach (var doc in resultList)
                {
                    if (!(doc.uploadedBy).Equals("EDMS"))   //SHOULD REMOVE WHEN EDMS BDOCUMENT ISSUE IS FIXED
                    {
                        var byteArr = GetBytesProxy(bizServer, token, doc.id.ToString(), 9999);
                        imgByteArr.Add(byteArr);
                    }
                }
            }
            //var jsonString = new JavaScriptSerializer().Serialize(imgByteArr);
            //Console.WriteLine(jsonString);

            return(imgByteArr);
        }
Пример #4
0
        private static bool UserHasProfile()
        {
            // Acquire permissions to read the one key we care about from the registry
            // Acquite permission to query the current user identity
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPrincipal));
            permissionSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read,
                                                               _fullProfileListKeyName));
            permissionSet.Assert();

            bool        userHasProfile = false;
            RegistryKey userProfileKey = null;

            try
            {
                // inspect registry and look for user profile via SID
                string userSid = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
                userProfileKey = Registry.LocalMachine.OpenSubKey(_profileListKeyName + @"\" + userSid);
                userHasProfile = userProfileKey != null;
            }
            finally
            {
                if (userProfileKey != null)
                {
                    userProfileKey.Close();
                }

                CodeAccessPermission.RevertAssert();
            }

            return(userHasProfile);
        }
Пример #5
0
        static XmlILModule()
        {
            AssemblyName    asmName;
            AssemblyBuilder asmBldr;

            CreateModulePermissionSet = new PermissionSet(PermissionState.None);
            // CreateDelegate demands MemberAccess permission
            CreateModulePermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            // DynamicMethod constructor demands ControlEvidence permissions.
            // Emitting symbols in DefineDynamicModule (to allow to debug the stylesheet) requires UnmanagedCode permission.
            CreateModulePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.UnmanagedCode));

            AssemblyId = 0;

            // 1. LRE assembly only needs to execute
            // 2. No temp files need be created
            // 3. Never allow assembly to Assert permissions
            asmName = CreateAssemblyName();
            asmBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);

            try {
                CreateModulePermissionSet.Assert();

                // Add custom attribute to assembly marking it as security transparent so that Assert will not be allowed
                // and link demands will be converted to full demands.
                asmBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.Transparent, new object[] {}));

                // Store LREModule once.  If multiple threads are doing this, then some threads might get different
                // modules.  This is OK, since it's not mandatory to share, just preferable.
                LREModule = asmBldr.DefineDynamicModule("System.Xml.Xsl.CompiledQuery", false);
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
        }
Пример #6
0
        public static Byte[] GetInspectionSignature(string inspectionid, string type, string bizServer, string userId, string password)
        {
            PermissionSet ps = new PermissionSet(PermissionState.None);

            ps.AddPermission(new WebPermission(PermissionState.Unrestricted));
            ps.AddPermission(new WebPermission(NetworkAccess.Accept, bizServer));
            ps.AddPermission(new WebPermission(NetworkAccess.Connect, bizServer));
            ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Execution));
            ps.Assert();

            var token = Authenticate(inspectionid, bizServer, userId, password);
            var docId = "";

            if (type.Equals("contractor"))
            {
                docId = GetInspectionContractorSign(bizServer, inspectionid, token);
            }
            else if (type.Equals("inspector"))
            {
                docId = GetInspectionInspectorSign(bizServer, inspectionid, token);
            }

            var byteArr = GetBytesProxy(bizServer, token, docId, 9999);

            return(byteArr);
        }
Пример #7
0
        private Uri GetEntryAssemblyLocation()
        {
            Uri entryLocation = null;

            System.Security.PermissionSet permissionSet = new PermissionSet(null);
            permissionSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            permissionSet.Assert();
            try
            {
                entryLocation = new Uri(Application.ResourceAssembly.CodeBase);
            }
            catch (Exception ex)
            {
                if (CriticalExceptions.IsCriticalException(ex))
                {
                    throw;
                }
                // `Swallow any other exceptions to avoid disclosing the critical path.
                //
                // Possible Exceptions: ArgumentException, ArgumentNullException, PathTooLongException
                // DirectoryNotFoundException, IOException, UnauthorizedAccessException,
                // ArgumentOutOfRangeException, FileNotFoundException, NotSupportedException
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            return(entryLocation);
        }
Пример #8
0
        Delegate RecreateCallback(Type delegateType, MethodInfo callbackMethod)
        {
            object targetInstance = null;

            // If the declaring type does not derive from Activity, somebody has manipulated the callback in the persistece store.
            if (!typeof(Activity).IsAssignableFrom(callbackMethod.DeclaringType))
            {
                return(null);
            }

            if (!callbackMethod.IsStatic)
            {
                targetInstance = this.ActivityInstance.Activity;
            }

            // Asserting ReflectionPermission.MemberAccess because the callback method is most likely internal or private
            if (ReflectionMemberAccessPermissionSet == null)
            {
                PermissionSet myPermissionSet = new PermissionSet(PermissionState.None);
                myPermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
                Interlocked.CompareExchange(ref ReflectionMemberAccessPermissionSet, myPermissionSet, null);
            }
            ReflectionMemberAccessPermissionSet.Assert();
            try
            {
                return(Delegate.CreateDelegate(delegateType, targetInstance, callbackMethod));
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
Пример #9
0
        public void RevertAssert_WithAssertion()
        {
            PermissionSet ups = new PermissionSet(PermissionState.Unrestricted);

            ups.Assert();
            PermissionSet.RevertAssert();
        }
Пример #10
0
 /// <SecurityNote>
 /// Critical: Asserts Full Trust. We are relying on our safe caller to have demanded _xamlLoadPermission
 /// </SecurityNote>
 private DynamicMethod CreateDynamicMethod(string name, Type returnType, params Type[] argTypes)
 {
     // Need to assert FullTrust because DynamicMethod.ctor demands the entire grant set of
     // the target assembly, which may be FullTrust
     if (s_FullTrustPermission == null)
     {
         s_FullTrustPermission = new PermissionSet(PermissionState.Unrestricted);
     }
     s_FullTrustPermission.Assert();
     try
     {
         if (_localType != null)
         {
             return(new DynamicMethod(name, returnType, argTypes, _localType));
         }
         else
         {
             return(new DynamicMethod(name, returnType, argTypes, _localAssembly.ManifestModule));
         }
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
 }
Пример #11
0
        public void Open()
        {
            if (State != CommunicationState.Created)
            {
                return;
            }
            try
            {
                Opening(this, EventArgs.Empty);

                //Permission required to read the providers application name and access config
                PermissionSet permissions = new PermissionSet(PermissionState.None);
                permissions.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));
                permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

                permissions.Assert();

                m_ServiceHostActivator.MembershipApplicationName = Membership.ApplicationName;
                if (Roles.Enabled)
                {
                    m_ServiceHostActivator.RolesApplicationName = Roles.ApplicationName;
                }
                PermissionSet.RevertAssert();

                m_ServiceHostActivator.Open();

                State = CommunicationState.Opened;

                Opened(this, EventArgs.Empty);
            }
            catch
            {
                State = CommunicationState.Faulted;
            }
        }
Пример #12
0
        public static void Main()
        {
            // Setting the AppDomainSetup. It is very important to set the ApplicationBase to a folder other than the one in which the sandboxer resides.
            var appDomainSetup = new AppDomainSetup
            {
                ApplicationBase = Path.GetFullPath(PathToUntrusted)
            };

            // Setting the permissions for the AppDomain. We give the permission to execute and to read/discover the location where the untrusted code is loaded.
            var permSet = new PermissionSet(PermissionState.None);

            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            // Microsoft Dynamics CRM allows outbound calls to a limited pattern of hostnames, source: https://msdn.microsoft.com/en-us/library/gg334752.aspx#Anchor_0
            permSet.AddPermission(new WebPermission(NetworkAccess.Connect, new Regex(@"^http[s]?://(?!((localhost[:/])|(\[.*\])|([0-9]+[:/])|(0x[0-9a-f]+[:/])|(((([0-9]+)|(0x[0-9A-F]+))\.){3}(([0-9]+)|(0x[0-9A-F]+))[:/]))).+", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant)));
            permSet.Assert();

            // We want the sandboxer assembly's strong name, so that we can add it to the full trust list.
            var fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence <StrongName>();

            // Now we have everything we need to create the AppDomain, so let's create it.
            var newDomain = AppDomain.CreateDomain("Sandbox", null, appDomainSetup, permSet, fullTrustAssembly);

            // Use CreateInstanceFrom to load an instance of the Sandboxer class into the new AppDomain.
            var handle = Activator.CreateInstanceFrom(newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandboxer).FullName);

            // Unwrap the new domain instance into a reference in this domain and use it to execute the untrusted code.
            var newDomainInstance = (Sandboxer)handle.Unwrap();

            newDomainInstance.ExecuteUntrustedCode(UntrustedAssembly, UntrustedClass, EntryPoint);
        }
Пример #13
0
        private static object LoadExtensionFor(string name)
        {
            // The docs claim that Activator.CreateInstance will create an instance
            // of an internal type provided that (a) the caller has ReflectionPermission
            // with the RestrictedMemberAccess flag, and (b) the grant set of the
            // calling assembly (WindowsBase) is a superset of the grant set of the
            // target assembly (one of our extension assemblies).   Both those conditions
            // are satisfied, yet the call still results in a security exception when run
            // under partial trust (specifically, in the PT environment created by
            // the WPF test infrastructure).   The only workaround I've found is to
            // assert full trust.
            PermissionSet ps = new PermissionSet(PermissionState.Unrestricted);

            ps.Assert();

            // build the full display name of the extension assembly
            string assemblyName          = Assembly.GetExecutingAssembly().FullName;
            string extensionAssemblyName = assemblyName.Replace("WindowsBase", "PresentationFramework-" + name)
                                           .Replace(BuildInfo.WCP_PUBLIC_KEY_TOKEN, BuildInfo.DEVDIV_PUBLIC_KEY_TOKEN);
            string       extensionTypeName = "MS.Internal." + name + "Extension";
            ObjectHandle handle;

            // create the instance of the extension class
            try
            {
                handle = Activator.CreateInstance(extensionAssemblyName, extensionTypeName);
            }
            catch (FileNotFoundException)
            {
                // if the extension assembly is missing, just return null
                handle = null;
            }

            return((handle != null) ? handle.Unwrap() : null);
        }
 private static AssemblyName GetName(Assembly assembly, bool copyName)
 {
     PermissionSet set = new PermissionSet(PermissionState.None);
     set.AddPermission(new System.Security.Permissions.FileIOPermission(PermissionState.Unrestricted));
     set.Assert();
     return assembly.GetName(copyName);
 }
        internal IContract GetContract()
        {
            if (_contract != null)
            {
                return(_contract);
            }

            // in direct connect, the contract has not been created.  Create it now.
            Object hav = _havReference.Target;

            if (hav == null)
            {
                throw new InvalidOperationException(Res.AddInNoLongerAvailable);
            }

            // Assert permission to the contracts, AddInSideAdapters, AddInViews and specific Addin directories only.
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
                                                             Path.Combine(_token.PipelineRootDirectory, AddInStore.ContractsDirName)));
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
                                                             Path.Combine(_token.PipelineRootDirectory, AddInStore.AddInAdaptersDirName)));
            permissionSet.Assert();

            Assembly.LoadFrom(_token._contract.Location);
            Assembly addinAdapterAssembly = Assembly.LoadFrom(_token._addinAdapter.Location);

            CodeAccessPermission.RevertAssert();

            // Create the AddIn adapter for the addin
            ActivationWorker worker = new ActivationWorker(_token);

            _contract = worker.CreateAddInAdapter(hav, addinAdapterAssembly);
            return(_contract);
        }
        static AssemblyName GetName(Assembly assembly, bool copyName)
        {
            PermissionSet perms = new PermissionSet(PermissionState.None);

            perms.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            perms.Assert();
            return(assembly.GetName(copyName));
        }
Пример #17
0
        public void Evaluate(string code)
        {
            CSharpCodeProvider compiler = new CSharpCodeProvider();


            int[] bleh = { 0, 1, 2, 3 };

            StringBuilder sb = new StringBuilder();

            sb.Append(codePrefix);
            sb.Append(code);
            sb.Append(codePostfix);
            PermissionSet perm = new PermissionSet(PermissionState.None);

            perm.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            perm.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            perm.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

            perm.Assert();
            //Assembly.LoadFrom(typeof(Evaluator).Assembly.ManifestModule.FullyQualifiedName);
            //AppDomain.CurrentDomain.Load(

            //CodeFinished=new CodeFinishedHandlerObject(delegate(object o,EventArgs ev){Console.WriteLine("hihihi");});
            CompilerParameters options = new CompilerParameters();

            options.GenerateExecutable = false;
            options.GenerateInMemory   = true;
            options.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            options.ReferencedAssemblies.Add("System.Xml.dll");
            options.ReferencedAssemblies.Add("System.Core.dll");
            if (extra != null)
            {
                options.ReferencedAssemblies.Add(extra);
            }
            //options.OutputAssembly=".\\bleh.dll";
            CompilerResults result = compiler.CompileAssemblyFromSource(options, sb.ToString());

            if (result.Errors.Count > 0)
            {
                Console.WriteLine(result.Errors[0].ToString());
                //CodeFinished.OnCodeFinished();
                throw new Exception("compile failed");
            }
            CodeAccessPermission.RevertAssert();
            //Assembly source=Assembly.Load("bleh");
            Assembly source;

            source = result.CompiledAssembly;
            Object  target = source.CreateInstance("Bleh");
            dynamic d      = target;

            testThread = new Thread(new ThreadStart(delegate(){ output = d.function(); OnCodeFinished(); }));
            testThread.Start();
        }
        public AddInServerWorker()
        {
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPrincipal));
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            permissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
            permissionSet.Assert();

            // without this call to initialize the client channel, this object cannot be remoted
            RemotingHelper.InitializeClientChannel();
        }
Пример #19
0
 /// <summary>
 /// DemandSuccedsAfterAssert
 /// </summary>
 /// <param name="toAssert"></param>
 /// <param name="toDemand"></param>
 /// <returns>true if assert stopped demand; false if assert didn't stop demand</returns>
 internal static bool DemandSuccedsAfterAssert(PermissionSet toAssert, PermissionSet toDemand)
 {
     toAssert.Assert();
     try
     {
         TransparentSecurityHelper.Demand(toDemand);
         return(true);
     }
     catch (SecurityException)
     {
         return(false);
     }
 }
Пример #20
0
        public void SetCodeFinishedHandler(CodeFinishedHandlerObject handler)
        {
            PermissionSet perm = new PermissionSet(PermissionState.None);

            perm.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            perm.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            perm.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

            perm.Assert();
            CodeFinished = (CodeFinishedHandlerObject)handler;

            CodeAccessPermission.RevertAssert();
        }
Пример #21
0
        /// <summary>
        /// Gets the IIS Anonimous user WindowsIdentity.
        /// </summary>
        /// <remarks>
        /// Use IIS to configure the anonymous user account as the trusted alternate identity.<para/>
        /// Then use this method to get a <see cref="WindowsIdentity"/> instance with impersonation token using the anonymous IIS account.<para/>		///
        /// </remarks>
        /// <note type="note">
        /// This approach assumes Forms or Passport authentication where your application’s virtual
        /// directory is configured in IIS to support anonymous access.<para/>
        /// The code demands the unmanaged code permission SecurityPermission(SecurityPermissionFlag.UnmanagedCode),<para/>
        /// which is granted only to fully trusted Web applications.
        /// </note>
        /// <exception cref="HttpException">Http current context is null.</exception>
        /// <example>If you use this code, use the following <b>&lt;identity&gt;</b> configuration:
        /// <code lang="C#">
        /// &lt;identity impersonate="false" /&gt;
        /// </code>
        /// </example>
        /// <returns>A <see cref="WindowsIdentity"/> instance for the account used for anonymous access.</returns>
        /// <permission cref="SecurityPermission">Demand for <see cref="SecurityPermissionFlag.ControlPrincipal"/> permission flag.</permission>
        public static WindowsIdentity LogonUser()
        {
            HttpContext context = HttpContext.Current;

            if (context == null)
            {
                throw new HttpException(Resource.ResourceManager[Resource.MessageKey.NullContextException]);
            }

            // Demand permissions
            new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Demand();
            // Assert permissions
            _assertedPermissions.Assert();

            try
            {
                // Get the service provider from the context
                IServiceProvider iServiceProvider = context as IServiceProvider;

                //Get a Type which represents an HttpContext
                Type httpWorkerRequestType = typeof(HttpWorkerRequest);

                // Get the HttpWorkerRequest service from the service provider
                // NOTE: When trying to get a HttpWorkerRequest type from the HttpContext
                // unmanaged code permission is demanded.
                HttpWorkerRequest httpWorkerRequest = iServiceProvider.GetService(httpWorkerRequestType) as HttpWorkerRequest;

                // Get the token passed by IIS
                IntPtr ptrUserToken = httpWorkerRequest.GetUserToken();

                // Create a WindowsIdentity from the token
                return(new WindowsIdentity(ptrUserToken, "NTLM", WindowsAccountType.Normal, true));
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
Пример #22
0
        internal static string GetTempAssemblyPath(string baseDir, Assembly assembly, string defaultNamespace)
        {
            if (assembly.IsDynamic)
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlPregenAssemblyDynamic));
            }

            PermissionSet perms = new PermissionSet(PermissionState.None);

            perms.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            perms.Assert();

            try {
                if (baseDir != null && baseDir.Length > 0)
                {
                    // check that the dirsctory exists
                    if (!Directory.Exists(baseDir))
                    {
                        throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingDirectory, baseDir));
                    }
                }
                else
                {
                    baseDir = Path.GetTempPath();
                    // check that the dirsctory exists
                    if (!Directory.Exists(baseDir))
                    {
                        throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingTempDirectory));
                    }
                }

#if MONO
                baseDir = Path.Combine(baseDir, GetTempAssemblyName(assembly.GetName(), defaultNamespace));
#else
                if (baseDir.EndsWith("\\", StringComparison.Ordinal))
                {
                    baseDir += GetTempAssemblyName(assembly.GetName(), defaultNamespace);
                }
                else
                {
                    baseDir += "\\" + GetTempAssemblyName(assembly.GetName(), defaultNamespace);
                }
#endif
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
            return(baseDir + ".dll");
        }
Пример #23
0
            void InitDynamicModule(string asmName)
            {
                // See http://blogs.msdn.com/Microsoft/archive/2005/02/03/366429.aspx for a simple example
                // of debuggable reflection-emit.
                Fx.Assert(dynamicModule == null, "can only be initialized once");

                // create a dynamic assembly and module
                AssemblyName assemblyName = new AssemblyName();

                assemblyName.Name = asmName;

                AssemblyBuilder assemblyBuilder;

                // The temporary assembly needs to be Transparent.
                ConstructorInfo transparentCtor =
                    typeof(SecurityTransparentAttribute).GetConstructor(
                        Type.EmptyTypes);
                CustomAttributeBuilder transparent = new CustomAttributeBuilder(
                    transparentCtor,
                    new Object[] { });

                assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run, null, true, new CustomAttributeBuilder[] { transparent });

                // Mark generated code as debuggable.
                // See http://blogs.msdn.com/rmbyers/archive/2005/06/26/432922.aspx for explanation.
                Type                   debuggableAttributeType = typeof(DebuggableAttribute);
                ConstructorInfo        constructorInfo         = debuggableAttributeType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
                CustomAttributeBuilder builder = new CustomAttributeBuilder(constructorInfo, new object[] {
                    DebuggableAttribute.DebuggingModes.DisableOptimizations |
                    DebuggableAttribute.DebuggingModes.Default
                });

                assemblyBuilder.SetCustomAttribute(builder);

                // We need UnmanagedCode permissions because we are asking for Symbols to be emitted.
                // We are protecting the dynamicModule so that only Critical code modifies it.
                PermissionSet unmanagedCodePermissionSet = new PermissionSet(PermissionState.None);

                unmanagedCodePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
                unmanagedCodePermissionSet.Assert();
                try
                {
                    dynamicModule = assemblyBuilder.DefineDynamicModule(asmName, true); // <-- pass 'true' to track debug info.
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }
            }
Пример #24
0
        private static string GetApplicationInstanceId(this Assembly entry)
        {
            var set = new PermissionSet(PermissionState.None);

            set.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            set.Assert();

            var typeLibGuidForAssembly = Marshal.GetTypeLibGuidForAssembly(entry);
            var strArray = entry.GetName().Version.ToString().Split(".".ToCharArray());

            PermissionSet.RevertAssert();

            return(typeLibGuidForAssembly + strArray[0] + "." + strArray[1]);
        }
Пример #25
0
        private string GetApplicationInstanceID()
        {
            var permissionSet    = new PermissionSet(PermissionState.None);
            var fileIoPermission = new FileIOPermission(PermissionState.Unrestricted);

            permissionSet.AddPermission(fileIoPermission);
            var securityPermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            permissionSet.AddPermission(securityPermission);
            permissionSet.Assert();
            var libGuidForAssembly = ProductInfo.ProductId;
            var strArray           = ProductInfo.Version.ToString().Split(Conversions.ToCharArrayRankOne("."));

            PermissionSet.RevertAssert();
            return(libGuidForAssembly + strArray[0] + "." + strArray[1]);
        }
Пример #26
0
        /// <summary>
        /// Wrap a delegate around a MethodInfo of the specified name and type and return it.
        /// </summary>
        public Delegate CreateDelegate(string name, Type typDelegate)
        {
            try {
                // CreateDelegate demands MemberAccess permission
                CreateDelegatePermissionSet.Assert();

                if (!this.useLRE)
                {
                    return(Delegate.CreateDelegate(typDelegate, (MethodInfo)this.methods[name]));
                }

                return(((DynamicMethod)this.methods[name]).CreateDelegate(typDelegate));
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
        }
Пример #27
0
        internal static void LoadContractAndHostAdapter(ContractComponent contract, HostAdapter hostAdapter,
                                                        out Type contractType, out Type hostAdapterType)
        {
            PermissionSet assertSet = new PermissionSet(PermissionState.None);

            assertSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, hostAdapter.Location));
            assertSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, contract.Location));
            assertSet.Assert();

            // Explicitly load the host adapter & contract first, using LoadFrom
            // to ensure they are loaded in the same loader context.
            Assembly hostAdapterAssembly = Assembly.LoadFrom(hostAdapter.Location);
            Assembly contractAssembly    = Assembly.LoadFrom(contract.Location);

            hostAdapterType = hostAdapterAssembly.GetType(hostAdapter.TypeInfo.FullName, true);
            contractType    = contractAssembly.GetType(contract.TypeInfo.FullName, true);
        }
 static private string MachineName() {
     try { // try-filter-finally so and catch-throw
         PermissionSet ps = new PermissionSet(PermissionState.None);
         ps.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
         ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
         ps.Assert(); // MDAC 62038
         try {
             return Environment.MachineName;
         }
         finally { // RevertAssert w/ catch-throw
             CodeAccessPermission.RevertAssert();
         }
     }
     catch { // MDAC 80973, 81286
         throw;
     }
 }
Пример #29
0
        internal static string GetTempAssemblyPath(string baseDir, Assembly assembly, string defaultNamespace)
        {
            if (assembly.IsDynamic)
            {
                throw new InvalidOperationException(Res.GetString("XmlPregenAssemblyDynamic"));
            }
            PermissionSet set = new PermissionSet(PermissionState.None);

            set.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            set.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            set.Assert();
            try
            {
                if ((baseDir != null) && (baseDir.Length > 0))
                {
                    if (!Directory.Exists(baseDir))
                    {
                        throw new UnauthorizedAccessException(Res.GetString("XmlPregenMissingDirectory", new object[] { baseDir }));
                    }
                }
                else
                {
                    baseDir = Path.GetTempPath();
                    if (!Directory.Exists(baseDir))
                    {
                        throw new UnauthorizedAccessException(Res.GetString("XmlPregenMissingTempDirectory"));
                    }
                }
                if (baseDir.EndsWith(@"\", StringComparison.Ordinal))
                {
                    baseDir = baseDir + GetTempAssemblyName(assembly.GetName(), defaultNamespace);
                }
                else
                {
                    baseDir = baseDir + @"\" + GetTempAssemblyName(assembly.GetName(), defaultNamespace);
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            return(baseDir + ".dll");
        }
Пример #30
0
        private Cursor GetCursor(int cursorID)
        {
            Invariant.Assert(cursorID == c_SPLIT || cursorID == c_SPLITOPEN, "incorrect cursor type");

            Cursor cursor = null;

            System.IO.Stream           stream   = null;
            System.Reflection.Assembly assembly = this.GetType().Assembly;

            if (cursorID == c_SPLIT)
            {
                stream = assembly.GetManifestResourceStream("split.cur");
            }
            else if (cursorID == c_SPLITOPEN)
            {
                stream = assembly.GetManifestResourceStream("splitopen.cur");
            }

            Debug.Assert(stream != null, "stream is null");
            if (stream != null)
            {
                PermissionSet permissions = new PermissionSet(null);

                FileIOPermission filePermission = new FileIOPermission(PermissionState.None);
                filePermission.AllLocalFiles = FileIOPermissionAccess.Write;
                permissions.AddPermission(filePermission);

                permissions.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
                permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
                permissions.Assert();

                try
                {
                    cursor = new Cursor(stream);
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }
            }

            return(cursor);
        }
Пример #31
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();
 }