Example #1
0
        /// <summary>
        /// return the appdomain with permission set in medium trust level
        /// </summary>
        /// <returns> appdomain</returns>
        private AppDomain GetCustomizedAppDomain()
        {
            AppDomainSetup setup = new AppDomainSetup {
                ApplicationBase = Environment.CurrentDirectory
            };

            setup.AppDomainInitializer = SetupAppDomain;
            var          ps      = new PermissionSet(PermissionState.None);
            StreamReader fs      = new StreamReader("AstoriaClientTest_MediumTrustPermissionSet.xml");
            string       strPerm = fs.ReadToEnd();

            strPerm = strPerm.Replace("$AppDir$", Environment.CurrentDirectory);
            ps.FromXml(SecurityElement.FromString(strPerm));
            AddPermissionByTest(ps);

            StrongName framework  = Assembly.GetExecutingAssembly().Evidence.GetHostEvidence <StrongName>();
            StrongName moduleCore = typeof(TestItem).Assembly.Evidence.GetHostEvidence <StrongName>();
            StrongName kokomo     = typeof(ModelEngineOptions).Assembly.Evidence.GetHostEvidence <StrongName>();

            StrongName[] sn = { framework, moduleCore, kokomo };

            AppDomain myDomain = AppDomain.CreateDomain("myDomain", null, setup, ps, sn);

            return(myDomain);
        }
        private PermissionSet getPermissionSet(AGIScriptMappingElement scriptMapping)
        {
            PermissionSet permission = null;

            switch (scriptMapping.PermissionSet)
            {
            case ScriptPermissionSet.FullTrust:
                permission = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("FullTrust");
                break;

            case ScriptPermissionSet.Internet:
                permission = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("Internet");
                break;

            case ScriptPermissionSet.Intranet:
                permission = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("Intranet");
                break;

            case ScriptPermissionSet.Host:
                permission = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet;
                break;

            case ScriptPermissionSet.Custom:
                permission = new PermissionSet(PermissionState.None);
                permission.FromXml(scriptMapping.CustomPermissionSet.SecurityElement);
                break;
            }

            return(permission);
        }
Example #3
0
        public static SecurityConfig Load()
        {
            SecurityConfig scfg = new SecurityConfig();

            TextReader tr = null;

            try
            {
                tr = File.OpenText(DefaultConfigFile);
                string        xml = tr.ReadToEnd();
                PermissionSet ps  = new PermissionSet(null);
                ps.FromXml(SecurityElement.FromString(xml));
                scfg._GridThreadPermissions = ps;
            }
            finally
            {
                try
                {
                    if (tr != null)
                    {
                        tr.Close();
                    }
                }
                catch { }
            }
            return(scfg);
        }
        private PermissionSet getAddinPermissionSet(SecurityElement securityElement)
        {
            PermissionSet permission = new PermissionSet(null);

            permission.FromXml(securityElement);

            return(permission);
        }
        // Token: 0x060025E9 RID: 9705 RVA: 0x000886A0 File Offset: 0x000868A0
        private PermissionSet ParsePermissionSet(Parser parser)
        {
            SecurityElement topElement    = parser.GetTopElement();
            PermissionSet   permissionSet = new PermissionSet(PermissionState.None);

            permissionSet.FromXml(topElement);
            return(permissionSet);
        }
Example #6
0
        public static PluginHost Create(string pluginId, IDictionary <string, object> config)
        {
            var currentDirectory = Directory.GetCurrentDirectory();

            var setup = new AppDomainSetup
            {
                ApplicationBase          = currentDirectory,
                ApplicationName          = pluginId,
                ConfigurationFile        = "", // DO not set to empty string if we want to use the conf file from this domain
                DisallowBindingRedirects = true,
                DisallowCodeDownload     = true,
                DisallowPublisherPolicy  = true
            };

            var permissions = new PermissionSet(PermissionState.None);

            if (config.ContainsKey("Permissions") && config["Permissions"] != null)
            {
                var securityElement = SecurityElement.FromString(config["Permissions"].ToString());

                if (securityElement != null)
                {
                    permissions.FromXml(securityElement);
                }
            }

            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence // To get nice exceptions with permission demands.
                                                             | SecurityPermissionFlag.ControlPolicy // See ^
                                                             | SecurityPermissionFlag.Execution     // To allow the plugin to execute
                                                             ));


            // WCF hosting for JSONRPC
            permissions.AddPermission(new WebPermission(NetworkAccess.Connect | NetworkAccess.Accept,
                                                        new Regex(@"http://localhost:31337/hadouken\.plugins.*")));

            // Isolated storage
            permissions.AddPermission(new IsolatedStorageFilePermission(PermissionState.Unrestricted));

            var ev = new Evidence(new EvidenceBase[] { new Url(config["Url"].ToString()) }, null);

            var fxAsm  = Assembly.LoadFile(Path.Combine(currentDirectory, FxAssembly));
            var domain = AppDomain.CreateDomain(pluginId, ev, setup, permissions,
                                                typeof(PluginHost).Assembly.Evidence.GetHostEvidence <StrongName>(),
                                                fxAsm.Evidence.GetHostEvidence <StrongName>());

            return((PluginHost)Activator.CreateInstanceFrom(
                       domain,
                       typeof(PluginHost).Assembly.ManifestModule.FullyQualifiedName,
                       typeof(PluginHost).FullName,
                       false,
                       BindingFlags.Default,
                       null,
                       new object[] { pluginId, config },
                       null,
                       null).Unwrap());
        }
Example #7
0
        /// <summary>
        /// Creates a PermissionSet from its xml'ed description
        /// </summary>
        /// <param name="s">xml string</param>
        /// <returns>a new PermissionSet</returns>
        internal static PermissionSet PermissionSetFromString(string s)
        {
            StringReader    reader  = new StringReader(s);
            SecurityElement secelem = SecurityElementBuilder.SecurityElementFromXml(reader);
            PermissionSet   perm    = new PermissionSet(PermissionState.None);

            perm.FromXml(secelem);
            return(perm);
        }
Example #8
0
 public static void PermissionRequestEvidenceCallMethods()
 {
     PermissionSet ps = new PermissionSet(new PermissionState());
     PermissionRequestEvidence pre = new PermissionRequestEvidence(ps, ps, ps);
     PermissionRequestEvidence obj = pre.Copy();
     string str = ps.ToString();
     SecurityElement se = new SecurityElement("");
     ps.FromXml(se);
     se = ps.ToXml();
 }
Example #9
0
        public static void PermissionRequestEvidenceCallMethods()
        {
            PermissionSet             ps  = new PermissionSet(new PermissionState());
            PermissionRequestEvidence pre = new PermissionRequestEvidence(ps, ps, ps);
            PermissionRequestEvidence obj = pre.Copy();
            string          str           = ps.ToString();
            SecurityElement se            = new SecurityElement("");

            ps.FromXml(se);
            se = ps.ToXml();
        }
        /// <include file='doc\PermissionRequestEvidence.uex' path='docs/doc[@for="PermissionRequestEvidence.char1"]/*' />
        /// <internalonly/>
        int IBuiltInEvidence.InitFromBuffer(char[] buffer, int position)
        {
            int numPermSets = BuiltInEvidenceHelper.GetIntFromCharArray(buffer, position);

            position += 2;

            int tempLength;

            for (int i = 0; i < numPermSets; i++)
            {
                char psKind = buffer[position++];

                tempLength = BuiltInEvidenceHelper.GetIntFromCharArray(buffer, position);
                position  += 2;

                String tempStr = new String(buffer, position, tempLength);
                position += tempLength;
                Parser p = new Parser(tempStr);

                PermissionSet psTemp = new PermissionSet();
                psTemp.FromXml(p.GetTopElement());

                switch (psKind)
                {
                case idRequest:
                    m_strRequest = tempStr;
                    m_request    = psTemp;
                    break;

                case idOptional:
                    m_strOptional = tempStr;
                    m_optional    = psTemp;
                    break;

                case idDenied:
                    m_strDenied = tempStr;
                    m_denied    = psTemp;
                    break;

                default:
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnableToFixup"));
                }
            }

            return(position);
        }
Example #11
0
        // Create a permission set object.
        public PermissionSet CreatePermissionSet()
        {
            PermissionSet   set;
            SecurityElement element;
            StreamReader    reader;
            String          buf;

            if (Unrestricted)
            {
                set = new PermissionSet(PermissionState.Unrestricted);
            }
            else if (name != null)
            {
                set = CreateBuiltinPermissionSet(name);
            }
            else if (file != null)
            {
                // Parse the contents of a file.
                reader = new StreamReader(file);
                buf    = reader.ReadToEnd();
                reader.Close();
                set     = new PermissionSet(PermissionState.None);
                element = SecurityElement.Parse(buf);
                if (element != null)
                {
                    set.FromXml(element);
                }
            }
            else if (xml != null)
            {
                // Parse the contents of a string.
                set     = new PermissionSet(PermissionState.None);
                element = SecurityElement.Parse(xml);
                if (element != null)
                {
                    set.FromXml(element);
                }
            }
            else
            {
                set = new PermissionSet(PermissionState.None);
            }
            return(set);
        }
Example #12
0
        static PermissionSet LoadPermissions(string filename)
        {
            SecurityElement se = LoadXml(filename);

            if (se == null)
            {
                return(null);
            }

            PermissionSet ps = new PermissionSet(PermissionState.None);

            ps.FromXml(se);
            if (se.Attribute("class").IndexOf("System.Security.NamedPermissionSet") == -1)
            {
                return(ps);
            }
            // now we know it's a NamedPermissionSet
            return((PermissionSet) new NamedPermissionSet(se.Attribute("Name"), ps));
        }
Example #13
0
        /// <summary>
        /// Creates a Sandbox object based on a TextReader containing an xml'ed permission set
        /// </summary>
        /// <param name="permissionSetStream">a text reader representing a xml'ed permission set</param>
        /// <param name="fullTrustAssembliesPath" />
        private void BuildSandbox(TextReader permissionSetStream, string fullTrustAssembliesPath)
        {
            PermissionSet permSet = null;

            // if there isn't a stream with a permission set, no sandbox => full trust permission set
            if (permissionSetStream != null)
            {
                //create permission set from stream
                SecurityElement secelem = SecurityElementBuilder.SecurityElementFromXml(permissionSetStream);
                permSet = new PermissionSet(PermissionState.None);
                permSet.FromXml(secelem);
            }
            else
            {
                permSet = new PermissionSet(PermissionState.Unrestricted);
            }

            //create sandbox app domain. This method doesn't use the full trust assemblies, they are used by the policy level
            CreateSandboxedDomain(permSet, fullTrustAssembliesPath);
        }
Example #14
0
        private PermissionSet CreateFromXml(string xml)
        {
#if !NET_2_1
            SecurityParser sp = new SecurityParser();
            try
            {
                sp.LoadXml(xml);
            }
            catch (Mono.Xml.SmallXmlParserException xe)
            {
                throw new XmlSyntaxException(xe.Line, xe.ToString());
            }
            SecurityElement se = sp.ToXml();

            string className = se.Attribute("class");
            if (className == null)
            {
                return(null);
            }

            PermissionState state = PermissionState.None;
            if (CodeAccessPermission.IsUnrestricted(se))
            {
                state = PermissionState.Unrestricted;
            }

            if (className.EndsWith("NamedPermissionSet"))
            {
                NamedPermissionSet nps = new NamedPermissionSet(se.Attribute("Name"), state);
                nps.FromXml(se);
                return((PermissionSet)nps);
            }
            else if (className.EndsWith("PermissionSet"))
            {
                PermissionSet ps = new PermissionSet(state);
                ps.FromXml(se);
                return(ps);
            }
#endif
            return(null);
        }
Example #15
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 #16
0
        public void FromXml(SecurityElement e, PolicyLevel level)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            if (e.Tag != "PolicyStatement")
            {
                throw new ArgumentException(Locale.GetText("Invalid tag."));
            }


            string attributes = e.Attribute("Attributes");

            if (attributes != null)
            {
                attrs = (PolicyStatementAttribute)Enum.Parse(
                    typeof(PolicyStatementAttribute), attributes);
            }

            SecurityElement permissions = e.SearchForChildByTag("PermissionSet");

            PermissionSet.FromXml(permissions);
        }
Example #17
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 #18
0
        /// <include file='doc\PolicyStatement.uex' path='docs/doc[@for="PolicyStatement.FromXml1"]/*' />
        public void FromXml(SecurityElement et, PolicyLevel level)
        {
            if (et == null)
            {
                throw new ArgumentNullException("et");
            }

            if (!et.Tag.Equals("PolicyStatement"))
            {
                throw new ArgumentException(String.Format(Environment.GetResourceString("Argument_InvalidXMLElement"), "PolicyStatement", this.GetType().FullName));
            }

            m_attributes = (PolicyStatementAttribute)0;

            String strAttributes = et.Attribute("Attributes");

            if (strAttributes != null)
            {
                m_attributes = (PolicyStatementAttribute)Enum.Parse(typeof(PolicyStatementAttribute), strAttributes);
            }

            lock (this)
            {
                m_permSet = null;

                if (level != null)
                {
                    String permSetName = et.Attribute("PermissionSetName");

                    if (permSetName != null)
                    {
                        m_permSet = level.GetNamedPermissionSetInternal(permSetName);

                        if (m_permSet == null)
                        {
                            m_permSet = new PermissionSet(PermissionState.None);
                        }
                    }
                }


                if (m_permSet == null)
                {
                    // There is no provided level, it is not a named permission set, or
                    // the named permission set doesn't exist in the provided level,
                    // so just create the class through reflection and decode normally.

                    SecurityElement e = et.SearchForChildByTag("PermissionSet");

                    if (e != null)
                    {
                        String className = e.Attribute("class");

                        if (className != null && (className.Equals("NamedPermissionSet") ||
                                                  className.Equals("System.Security.NamedPermissionSet")))
                        {
                            m_permSet = new NamedPermissionSet("DefaultName", PermissionState.None);
                        }
                        else
                        {
                            m_permSet = new PermissionSet(PermissionState.None);
                        }

                        try
                        {
                            // We play it conservative here and just say that we are loading policy
                            // anytime we have to decode a permission set.
                            bool fullyLoaded;
                            m_permSet.FromXml(e, true, out fullyLoaded);
                        }
                        catch (Exception)
                        {
                            // ignore any exceptions from the decode process.
                            // Note: we go ahead and use the permission set anyway.  This should be safe since
                            // the decode process should never give permission beyond what a proper decode would have
                            // given.
                        }
                    }
                    else
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
                    }
                }

                if (m_permSet == null)
                {
                    m_permSet = new PermissionSet(PermissionState.None);
                }
            }
        }
Example #19
0
        public void FromXml(SecurityElement e, PolicyLevel level)
        {
            if (null == e)
            {
                throw new ArgumentNullException("e");
            }

            PermissionSet ps       = null;
            string        psetname = e.Attribute("PermissionSetName");

            if ((psetname != null) && (level != null))
            {
                ps = level.GetNamedPermissionSet(psetname);
            }
            else
            {
                SecurityElement pset = e.SearchForChildByTag("PermissionSet");
                if (pset != null)
                {
                    Type classType = Type.GetType(pset.Attribute("class"));
                    ps = (PermissionSet)Activator.CreateInstance(classType, true);
                    ps.FromXml(pset);
                }
                else
                {
                    ps = new PermissionSet(new PermissionSet(PermissionState.None));
                }
            }
            m_policy = new PolicyStatement(ps);

            m_children.Clear();
            if ((e.Children != null) && (e.Children.Count > 0))
            {
                foreach (SecurityElement se in e.Children)
                {
                    if (se.Tag == "CodeGroup")
                    {
                        this.AddChild(CodeGroup.CreateFromXml(se, level));
                    }
                }
            }

            m_membershipCondition = null;
            SecurityElement mc = e.SearchForChildByTag("IMembershipCondition");

            if (mc != null)
            {
                string className = mc.Attribute("class");
                Type   classType = Type.GetType(className);
                if (classType == null)
                {
                    classType = Type.GetType("System.Security.Policy." + className);
                }
                m_membershipCondition = (IMembershipCondition)Activator.CreateInstance(classType, true);
                m_membershipCondition.FromXml(mc, level);
            }

            m_name        = e.Attribute("Name");
            m_description = e.Attribute("Description");

            // seems like we might need this to Resolve() in subclasses
            m_level = level;

            ParseXml(e, level);
        }
        /// <include file='doc\PermissionRequestEvidence.uex' path='docs/doc[@for="PermissionRequestEvidence.char1"]/*' />
        /// <internalonly/>
        int IBuiltInEvidence.InitFromBuffer( char[] buffer, int position )
        {
            int numPermSets = BuiltInEvidenceHelper.GetIntFromCharArray(buffer, position);
            position += 2;

            int tempLength;
            for (int i = 0; i < numPermSets; i++)
            {
                char psKind = buffer[position++];

                tempLength = BuiltInEvidenceHelper.GetIntFromCharArray(buffer, position);
                position += 2;

                String tempStr = new String(buffer, position, tempLength);
                position += tempLength;
                Parser p = new Parser( tempStr );

                PermissionSet psTemp = new PermissionSet();
                psTemp.FromXml(p.GetTopElement());

                switch(psKind)
                {
                    case idRequest:
                        m_strRequest = tempStr;
                        m_request = psTemp;
                        break;

                    case idOptional:
                        m_strOptional = tempStr;
                        m_optional = psTemp;
                        break;

                    case idDenied:
                        m_strDenied = tempStr;
                        m_denied = psTemp;
                        break;

                    default:
                        throw new SerializationException(Environment.GetResourceString("Serialization_UnableToFixup"));
                }
            }

            return position;
        }
Example #21
0
        /// <include file='doc\PermissionAttributes.uex' path='docs/doc[@for="PermissionSetAttribute.CreatePermissionSet"]/*' />
        public PermissionSet CreatePermissionSet()
        {
            if (m_unrestricted)
            {
                return new PermissionSet( PermissionState.Unrestricted );
            }
            if (m_name != null)
            {
                return PolicyLevel.GetBuiltInSet( m_name );
            }
            else if (m_file != null || m_xml != null)
            {
                Parser parser = null;
                
                if (m_file != null)
                {
                    Encoding[] encodings = new Encoding[] { null, Encoding.UTF8, Encoding.ASCII, Encoding.Unicode };

                    bool success = false;
                    Exception exception = null;
                    FileStream f = new FileStream( m_file, FileMode.Open, FileAccess.Read );

                    for (int i = 0; !success && i < encodings.Length; ++i)
                    {

                        try
                        {
                            f.Position = 0;

                            StreamReader reader;
                            if (encodings[i] != null)
                                reader = new StreamReader( f, encodings[i] );
                            else
                                reader = new StreamReader( f );

                            parser = new Parser( reader );
                            success = true;
                        }
                        catch (Exception e1)
                        {
                            if (exception == null)
                                exception = e1;
                        }
                    }

                    if (!success && exception != null)
                        throw exception;
                }
                else
                {
                    // Since we have a unicode string, we have to copy the bytes
                    // into a byte array and create a data reader.
                   
                    parser = new Parser( m_xml.ToCharArray() );
                }
            
                SecurityElement e = parser.GetTopElement();

                // Note: we can just assume this is a regular permission set because
                // the name and description are not used in declarative security.

                PermissionSet permSet = new PermissionSet( PermissionState.None );

                permSet.FromXml( e );

                return permSet;
            }
            else
            {
                return new PermissionSet( PermissionState.None );
            }
        }
        /// <include file='doc\PermissionAttributes.uex' path='docs/doc[@for="PermissionSetAttribute.CreatePermissionSet"]/*' />
        public PermissionSet CreatePermissionSet()
        {
            if (m_unrestricted)
            {
                return(new PermissionSet(PermissionState.Unrestricted));
            }
            if (m_name != null)
            {
                return(PolicyLevel.GetBuiltInSet(m_name));
            }
            else if (m_file != null || m_xml != null)
            {
                Parser parser = null;

                if (m_file != null)
                {
                    Encoding[] encodings = new Encoding[] { null, Encoding.UTF8, Encoding.ASCII, Encoding.Unicode };

                    bool       success   = false;
                    Exception  exception = null;
                    FileStream f         = new FileStream(m_file, FileMode.Open, FileAccess.Read);

                    for (int i = 0; !success && i < encodings.Length; ++i)
                    {
                        try
                        {
                            f.Position = 0;

                            StreamReader reader;
                            if (encodings[i] != null)
                            {
                                reader = new StreamReader(f, encodings[i]);
                            }
                            else
                            {
                                reader = new StreamReader(f);
                            }

                            parser  = new Parser(reader);
                            success = true;
                        }
                        catch (Exception e1)
                        {
                            if (exception == null)
                            {
                                exception = e1;
                            }
                        }
                    }

                    if (!success && exception != null)
                    {
                        throw exception;
                    }
                }
                else
                {
                    // Since we have a unicode string, we have to copy the bytes
                    // into a byte array and create a data reader.

                    parser = new Parser(m_xml.ToCharArray());
                }

                SecurityElement e = parser.GetTopElement();

                // Note: we can just assume this is a regular permission set because
                // the name and description are not used in declarative security.

                PermissionSet permSet = new PermissionSet(PermissionState.None);

                permSet.FromXml(e);

                return(permSet);
            }
            else
            {
                return(new PermissionSet(PermissionState.None));
            }
        }
Example #23
0
		private PermissionSet CreateFromXml (string xml) 
		{
#if !NET_2_1
			SecurityParser sp = new SecurityParser ();
			try {
				sp.LoadXml (xml);
			}
			catch (Mono.Xml.SmallXmlParserException xe) {
				throw new XmlSyntaxException (xe.Line, xe.ToString ());
			}
			SecurityElement se = sp.ToXml ();

			string className = se.Attribute ("class");
			if (className == null)
				return null;

			PermissionState state = PermissionState.None;
			if (CodeAccessPermission.IsUnrestricted (se))
				state = PermissionState.Unrestricted;

			if (className.EndsWith ("NamedPermissionSet")) {
				NamedPermissionSet nps = new NamedPermissionSet (se.Attribute ("Name"), state);
				nps.FromXml (se);
				return (PermissionSet) nps;
			}
			else if (className.EndsWith ("PermissionSet")) {
				PermissionSet ps = new PermissionSet (state);
				ps.FromXml (se);
				return ps;
			}
#endif
			return null;
		}
        private PermissionSet ParsePermissionSet(Parser parser)
        {
            SecurityElement e = parser.GetTopElement();
            PermissionSet permSet = new PermissionSet( PermissionState.None );
            permSet.FromXml( e );

            return permSet;
        }
Example #25
0
 public static void PermissionSetDemo()
 {
     Console.WriteLine("Executing PermissionSetDemo");
     try
     {
         //<Snippet2>
         // Open a new PermissionSet.
         PermissionSet ps1 = new PermissionSet(PermissionState.None);
         Console.WriteLine("Adding permission to open a file from a file dialog box.");
         //<Snippet3>
         // Add a permission to the permission set.
         ps1.AddPermission(
             new FileDialogPermission(FileDialogPermissionAccess.Open));
         //</Snippet3>
         Console.WriteLine("Demanding permission to open a file.");
         ps1.Demand();
         Console.WriteLine("Demand succeeded.");
         //</Snippet2>
         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 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"));
         //<Snippet4>
         // Demand all the permissions in the set.
         Console.WriteLine("Demand all permissions.");
         ps1.Demand();
         //</Snippet4>
         Console.WriteLine("Demand succeeded.");
         //<Snippet5>
         // Display the number of permissions in the set.
         Console.WriteLine("Number of permissions = " + ps1.Count);
         //</Snippet5>
         //<Snippet6>
         // Display the value of the IsSynchronized property.
         Console.WriteLine("IsSynchronized property = " + ps1.IsSynchronized);
         //</Snippet6>
         //<Snippet7>
         // Display the value of the IsReadOnly property.
         Console.WriteLine("IsReadOnly property = " + ps1.IsReadOnly);
         //</Snippet7>
         //<Snippet8>
         // Display the value of the SyncRoot property.
         Console.WriteLine("SyncRoot property = " + ps1.SyncRoot);
         //</Snippet8>
         //<Snippet9>
         // 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());
         //</Snippet9>
         //<Snippet10>
         Console.WriteLine("Value of the permission set ToString = \n" + ps1.ToString());
         //</Snippet10>
         PermissionSet ps2 = new PermissionSet(PermissionState.None);
         //<Snippet11>
         // 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"));
         IEnumerator list = ps1.GetEnumerator();
         Console.WriteLine("Permissions in first permission set:");
         while (list.MoveNext())
         {
             Console.WriteLine(list.Current.ToString());
         }
         Console.WriteLine("Second permission IsSubsetOf first permission = " + ps2.IsSubsetOf(ps1));
         //</Snippet11>
         //<Snippet12>
         // 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());
         //</Snippet12>
         // 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.Read |
                                  FileIOPermissionAccess.Write | FileIOPermissionAccess.Append,
                                  "C:\\Temp\\Testfile.txt"));
         //<Snippet13>
         // 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());
         //</Snippet13>
         //<Snippet15>
         // Remove FileIOPermission from the permission set.
         ps5.RemovePermission(typeof(FileIOPermission));
         Console.WriteLine("The last permission set after removing FileIOPermission = "
                           + ps5.ToString());
         //</Snippet15>
         //<Snippet16>
         // Change the permission set using SetPermission.
         ps5.SetPermission(new EnvironmentPermission(EnvironmentPermissionAccess.AllAccess, "USERNAME"));
         Console.WriteLine("Permission set after SetPermission = " + ps5.ToString());
         //</Snippet16>
         //<Snippet17>
         // 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");
         //</Snippet17>
         //<Snippet18>
         // Display results of PermissionSet.GetEnumerator.
         IEnumerator psEnumerator = ps1.GetEnumerator();
         while (psEnumerator.MoveNext())
         {
             Console.WriteLine(psEnumerator.Current);
         }
         //</Snippet18>
         //<Snippet19>
         // Check for an unrestricted permission set.
         PermissionSet ps7 = new PermissionSet(PermissionState.Unrestricted);
         Console.WriteLine("Permission set is unrestricted = " + ps7.IsUnrestricted());
         //</Snippet19>
         //<Snippet20>
         // Create and display a copy of a permission set.
         ps7 = ps5.Copy();
         Console.WriteLine("Result of copy = " + ps7.ToString());
         //</Snippet20>
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message.ToString());
     }
 }
Example #26
0
        [System.Security.SecurityCritical]  // auto-generated
        internal void FromXml(SecurityElement et, PolicyLevel level, bool allowInternalOnly)
        {
            if (et == null)
            {
                throw new ArgumentNullException(nameof(et));
            }

            if (!et.Tag.Equals("PolicyStatement"))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidXMLElement"), nameof(PolicyStatement), this.GetType().FullName));
            }
            Contract.EndContractBlock();

            m_attributes = (PolicyStatementAttribute)0;

            String strAttributes = et.Attribute("Attributes");

            if (strAttributes != null)
            {
                m_attributes = (PolicyStatementAttribute)Enum.Parse(typeof(PolicyStatementAttribute), strAttributes);
            }

            lock (this)
            {
                m_permSet = null;

                if (level != null)
                {
                    String permSetName = et.Attribute("PermissionSetName");

                    if (permSetName != null)
                    {
                        m_permSet = level.GetNamedPermissionSetInternal(permSetName);

                        if (m_permSet == null)
                        {
                            m_permSet = new PermissionSet(PermissionState.None);
                        }
                    }
                }


                if (m_permSet == null)
                {
                    // There is no provided level, it is not a named permission set, or
                    // the named permission set doesn't exist in the provided level,
                    // so just create the class through reflection and decode normally.

                    SecurityElement e = et.SearchForChildByTag("PermissionSet");

                    if (e != null)
                    {
                        String className = e.Attribute("class");

                        if (className != null && (className.Equals("NamedPermissionSet") ||
                                                  className.Equals("System.Security.NamedPermissionSet")))
                        {
                            m_permSet = new NamedPermissionSet("DefaultName", PermissionState.None);
                        }
                        else
                        {
                            m_permSet = new PermissionSet(PermissionState.None);
                        }

                        try
                        {
                            m_permSet.FromXml(e, allowInternalOnly, true);
                        }
                        catch
                        {
                            // ignore any exceptions from the decode process.
                            // Note: we go ahead and use the permission set anyway.  This should be safe since
                            // the decode process should never give permission beyond what a proper decode would have
                            // given.
                        }
                    }
                    else
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
                    }
                }

                if (m_permSet == null)
                {
                    m_permSet = new PermissionSet(PermissionState.None);
                }
            }
        }
Example #27
0
        // Implement the ISecurityPolicyEncodable interface.
        public void FromXml(SecurityElement et, PolicyLevel level)
        {
            if (et == null)
            {
                throw new ArgumentNullException("et");
            }
            if (et.Tag != "PolicyStatement")
            {
                throw new ArgumentException
                          (_("Security_PolicyName"));
            }
            if (et.Attribute("version") != "1")
            {
                throw new ArgumentException
                          (_("Security_PolicyVersion"));
            }
            String value = et.Attribute("Attributes");

            if (value != null)
            {
                attributes = (PolicyStatementAttribute)
                             Enum.Parse(typeof(PolicyStatementAttribute), value);
            }
            else
            {
                attributes = PolicyStatementAttribute.Nothing;
            }
            permSet = null;
            if (level != null)
            {
                String name = et.Attribute("PermissionSetName");
                if (name != null)
                {
                    permSet = level.GetNamedPermissionSet(value);
                    if (permSet == null)
                    {
                        permSet = new PermissionSet(PermissionState.None);
                    }
                }
            }
            if (permSet == null)
            {
                SecurityElement child;
                child = et.SearchForChildByTag("PermissionSet");
                if (child != null)
                {
                    String permClass;
                    permClass = child.Attribute("class");
                    if (permClass != null &&
                        permClass.IndexOf("NamedPermissionSet") != -1)
                    {
                        permSet = new NamedPermissionSet
                                      ("DefaultName", PermissionState.None);
                    }
                    else
                    {
                        permSet = new PermissionSet(PermissionState.None);
                    }
                    try
                    {
                        permSet.FromXml(child);
                    }
                    catch (Exception)
                    {
                        // Ignore errors during set loading.
                    }
                }
            }
            if (permSet == null)
            {
                permSet = new PermissionSet(PermissionState.None);
            }
        }