FromXml() public method

public FromXml ( SecurityElement et ) : void
et SecurityElement
return void
 private PermissionSet ParsePermissionSet(Parser parser)
 {
     SecurityElement topElement = parser.GetTopElement();
     PermissionSet set = new PermissionSet(PermissionState.None);
     set.FromXml(topElement);
     return set;
 }
Example #2
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 #3
0
        internal object ToSecurityObject()
        {
            if (!(this.m_strTag == "PermissionSet"))
            {
                return((object)this.ToPermission(false));
            }
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            permissionSet.FromXml(this);
            return((object)permissionSet);
        }
Example #4
0
        internal object ToSecurityObject()
        {
            string str;

            if (((str = this.m_strTag) != null) && (str == "PermissionSet"))
            {
                PermissionSet set = new PermissionSet(PermissionState.None);
                set.FromXml(this);
                return(set);
            }
            return(this.ToPermission(false));
        }
Example #5
0
        internal object ToSecurityObject()
        {
            string strTag;

            if ((strTag = this.m_strTag) != null && strTag == "PermissionSet")
            {
                PermissionSet permissionSet = new PermissionSet(PermissionState.None);
                permissionSet.FromXml(this);
                return(permissionSet);
            }
            return(this.ToPermission(false));
        }
        internal Object ToSecurityObject()
        {
            switch (m_strTag)
            {
            case "PermissionSet":
                PermissionSet pset = new PermissionSet(PermissionState.None);
                pset.FromXml(this);
                return(pset);

            default:
                return(ToPermission(false));
            }
        }
Example #7
0
        private static bool IsDataObjectFromLessPriviligedApplicationDomain(IDataObject dataObjectToApply)
        {
            bool   retVal           = false;
            object applicationTrust = null;
            // Extract the permission set in case of xaml cut and paste
            // extract permission set if it exists if not data came from full trust app and we do not care
            bool isApplicationTrustFormatPresent = false;

            isApplicationTrustFormatPresent = dataObjectToApply.GetDataPresent(DataFormats.ApplicationTrust, /*autoConvert:*/ false);
            if (isApplicationTrustFormatPresent)
            {
                applicationTrust = dataObjectToApply.GetData(DataFormats.ApplicationTrust, /*autoConvert:*/ false);
            }

            if (applicationTrust != null)
            {
                string applicationTrustText = null;
                // convert to string
                applicationTrustText = applicationTrust.ToString();


                // Convert string to permission set for getting permission set of source
                PermissionSet permissionSetSource;
                try
                {
                    SecurityElement securityElement = SecurityElement.FromString(applicationTrustText);
                    permissionSetSource = new System.Security.PermissionSet(PermissionState.None);
                    permissionSetSource.FromXml(securityElement);
                }
                catch (XmlSyntaxException)
                {
                    // This is the condition where we have Malformed XML in the clipboard for application trust
                    // here we will fail silently since we do not want to break arbitrary applications
                    // but since we cannot establish the validity of the application trust content we will fall back to
                    // whatever is more secure
                    return(true);
                }

                //extract permission set for the current appdomain which is target
                PermissionSet permissionSetDestination = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin();
                //Compare permissions sets
                if (!permissionSetDestination.IsSubsetOf(permissionSetSource))
                {
                    retVal = true; // in case target is not subset of source revert to unicode or text
                }
            }
            return(retVal);
        }
Example #8
0
 public void FromXml(SecurityElement el)
 {
     if (el == null)
     {
         throw new ArgumentNullException("el");
     }
     if (el.Tag != tagName)
     {
         string msg = String.Format("Invalid tag {0} expected {1}", el.Tag, tagName);
         throw new ArgumentException(msg, "el");
     }
     _list.Clear();
     if (el.Children != null)
     {
         foreach (SecurityElement child in el.Children)
         {
             PermissionSet ps = new PermissionSet(PermissionState.None);
             ps.FromXml(child);
             _list.Add(ps);
         }
     }
 }
Example #9
0
        internal static void ListHandler( String[] args )
        {
            if (args[0].Equals( "__internal_usage__" ))
            {
                Console.WriteLine( "SecDBEdit -list <file>\n    List database entries for file" );
                return;
            }
            
            if (args.Length < 2)
            {
                Error( "-list", "Not enough arguments", -1 );
            }
            
            ArrayList list = null;
            
            try
            {
                list = LoadDatabase( args[1] );
            }
            catch (Exception e)
            {
                Error( "-list", "Failed during load - " + e.Message, -1 );
            }

            for (int i = 0; i < list.Count; ++i)
            {
                Console.WriteLine( "**** Entry #" + (i+1) + " *********************" );
                
                if (((DatabaseEntry)list[i]).xml != null)
                {
                    Console.WriteLine( "XML:" );
                    if (IsSecAttr( ((DatabaseEntry)list[i]).xml) )
                        Console.WriteLine( SecAttrToPermSet( ((DatabaseEntry)list[i]).xml ).ToString() );
                    else
                        Console.WriteLine( GetElementFromUbyte( ((DatabaseEntry)list[i]).xml ).ToString() );
                }
                else
                {
                    Console.WriteLine( "No XML entry" );
                }
                
                if (((DatabaseEntry)list[i]).binary != null)
                {
                    String format = null;
                    PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);
                    try
                    {
                        if ( ((DatabaseEntry)list[i]).binary[0] == '<' )
                        {
                            permSet.FromXml( GetElementFromUbyte( ((DatabaseEntry)list[i]).binary ) );
                            format = "(XML)";
                        }
                        else
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            permSet = (PermissionSet)formatter.Deserialize( new MemoryStream( ((DatabaseEntry)list[i]).binary ) );
                            format = "(binary serialization)";
                        }
                    }
                    catch (Exception e)
                    {
                        Error( "-list", "Binary decode failed" + e.ToString(), -1 );
                    }
                    Console.WriteLine( "Binary " + format + ":" );
                    Console.WriteLine( permSet.ToXml().ToString() );
                }
                else
                {
                    Console.WriteLine( "No Binary entry - this equates to the empty set" );
                }
            }
        }
Example #10
0
        // FIXME little documentation in Fx 2.0 beta 1
        public static byte[] ConvertPermissionSet(string inFormat, byte[] inData, string outFormat)
        {
            if (inFormat == null)
            {
                throw new ArgumentNullException("inFormat");
            }
            if (outFormat == null)
            {
                throw new ArgumentNullException("outFormat");
            }
            if (inData == null)
            {
                return(null);
            }

            if (inFormat == outFormat)
            {
                return(inData);
            }

            PermissionSet ps = null;

            if (inFormat == "BINARY")
            {
                if (outFormat.StartsWith("XML"))
                {
                    using (MemoryStream ms = new MemoryStream(inData)) {
                        BinaryFormatter formatter = new BinaryFormatter();
                        ps = (PermissionSet)formatter.Deserialize(ms);
                        ms.Close();
                    }
                    string xml = ps.ToString();
                    switch (outFormat)
                    {
                    case "XML":
                    case "XMLASCII":
                        return(Encoding.ASCII.GetBytes(xml));

                    case "XMLUNICODE":
                        return(Encoding.Unicode.GetBytes(xml));
                    }
                }
            }
            else if (inFormat.StartsWith("XML"))
            {
                if (outFormat == "BINARY")
                {
                    string xml = null;
                    switch (inFormat)
                    {
                    case "XML":
                    case "XMLASCII":
                        xml = Encoding.ASCII.GetString(inData);
                        break;

                    case "XMLUNICODE":
                        xml = Encoding.Unicode.GetString(inData);
                        break;
                    }
                    if (xml != null)
                    {
                        ps = new PermissionSet(PermissionState.None);
                        ps.FromXml(SecurityElement.FromString(xml));

                        MemoryStream    ms        = new MemoryStream();
                        BinaryFormatter formatter = new BinaryFormatter();
                        formatter.Serialize(ms, ps);
                        ms.Close();
                        return(ms.ToArray());
                    }
                }
                else if (outFormat.StartsWith("XML"))
                {
                    string msg = String.Format(Locale.GetText("Can't convert from {0} to {1}"), inFormat, outFormat);
#if NET_2_0
                    throw new XmlSyntaxException(msg);
#else
                    throw new ArgumentException(msg);
#endif
                }
            }
            else
            {
                // unknown inFormat, returns null
                return(null);
            }
            // unknown outFormat, throw
            throw new SerializationException(String.Format(Locale.GetText("Unknown output format {0}."), outFormat));
        }
Example #11
0
      DecodeFromASCIIFile (String fileName,
                           String format)
      {
          if (fileName == null)
              return null ;
  
          PermissionSet permSet = new PermissionSet (false) ;
          
          try {
              FileStream fs = new FileStream (fileName, 
                                          FileMode.Open, 
                                          FileAccess.Read) ;
  #if _DEBUG
              if (debug)
                  DEBUG_WRITE("DecodeFromASCIIFile: Format = " + format + " File = " + fileName);
  #endif
              if (format == null || format.Equals( "XMLASCII" ))
              {
                  permSet.FromXml( new Parser( new BinaryReader( fs, Encoding.ASCII ) ).GetTopElement() );
              }
              else if (format.Equals( "XMLUNICODE" ))
              {
                  permSet.FromXml( new Parser( new BinaryReader( fs ) ).GetTopElement() );
              }
              else
              {
                  return null;
              }
          }
          catch (Exception)
          {
          }
 
          return null;
      }
		// [ExpectedException (typeof (ArgumentException))]
		public void FromXmlWrongVersion () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			SecurityElement se = ps.ToXml ();
			// can't modify - so we create our own
			SecurityElement se2 = new SecurityElement (se.Tag, se.Text);
			se2.AddAttribute ("class", se.Attribute ("class"));
			se2.AddAttribute ("version", "2");
			ps.FromXml (se2);
			// wow - here we accept a version 2 !!!
		}
		public void FromXmlNull () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			ps.FromXml (null);
		}
Example #14
0
        private static bool IsDataObjectFromLessPriviligedApplicationDomain(IDataObject dataObjectToApply) 
        {
            bool retVal = false; 
            object applicationTrust = null; 
            // Extract the permission set in case of xaml cut and paste
            // extract permission set if it exists if not data came from full trust app and we do not care 
            bool isApplicationTrustFormatPresent = false;
            isApplicationTrustFormatPresent = dataObjectToApply.GetDataPresent(DataFormats.ApplicationTrust, /*autoConvert:*/false);
            if (isApplicationTrustFormatPresent)
            { 
                applicationTrust = dataObjectToApply.GetData(DataFormats.ApplicationTrust, /*autoConvert:*/false);
            } 
 
            if (applicationTrust != null)
            { 
                string applicationTrustText = null;
                // convert to string
                applicationTrustText = applicationTrust.ToString();
 

                // Convert string to permission set for getting permission set of source 
                PermissionSet permissionSetSource; 
                try
                { 
                    SecurityElement securityElement = SecurityElement.FromString(applicationTrustText);
                    permissionSetSource = new System.Security.PermissionSet(PermissionState.None);
                    permissionSetSource.FromXml(securityElement);
                } 
                catch(XmlSyntaxException)
                { 
                    // This is the condition where we have Malformed XML in the clipboard for application trust 
                    // here we will fail silently since we do not want to break arbitrary applications
                    // but since we cannot establish the validity of the application trust content we will fall back to 
                    // whatever is more secure
                    return  true;
                }
 
                //extract permission set for the current appdomain which is target
                PermissionSet permissionSetDestination = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin(); 
                //Compare permissions sets 
                if (!permissionSetDestination.IsSubsetOf(permissionSetSource))
                { 
                    retVal = true; // in case target is not subset of source revert to unicode or text
                }
            }
            return retVal; 
        }
Example #15
0
        internal static void RegenHandler( String[] args )
        {
            if (args[0].Equals( "__internal_usage__" ))
            {
                Console.WriteLine( "SecDBEdit -regen <file> [{binary|xml}]\n    Regenerate translations for database entries with missing binary values" );
                return;
            }
            
            if (args.Length < 2)
            {
                Error( "-regen", "Not enough arguments", -1 );
            }

            bool useBinary = true;

            if (args.Length > 2 && String.Compare( args[2], "xml", true, CultureInfo.InvariantCulture ) == 0)
            {
                useBinary = false;
            }
            
            ArrayList list = null;
            
            try
            {
                list = LoadDatabase( args[1] );
            }
            catch (Exception e)
            {
                Error( "-regen", "Failed during load - " + e.Message, -1 );
            }
            
            for (int i = 0; i < list.Count; ++i)
            {
                if ((((DatabaseEntry)list[i]).xml != null))
                {
                    try
                    {
                        Console.WriteLine( "Adding binary value for entry #" + (i+1) + ":" );
                        PermissionSet pset;
                        if (IsSecAttr( ((DatabaseEntry)list[i]).xml))
                        {
                            pset = SecAttrToPermSet( ((DatabaseEntry)list[i]).xml );
                            Console.WriteLine( pset.ToString() );
                        }
                        else
                        {
                            SecurityElement elem = GetElementFromUbyte( ((DatabaseEntry)list[i]).xml );
                            Console.WriteLine( elem.ToString() );
                            pset = new PermissionSet( PermissionState.None );
                            pset.FromXml( elem );
                        }

                        byte[] bArray;

                        // These should be functionally identical to
                        // PermissionSet.EncodeBinary() and
                        // PermissionSet.EncodeXml()

                        if (useBinary)
                        {
                            MemoryStream stream = new MemoryStream();
                            BinaryFormatter formatter = new BinaryFormatter();
                            formatter.Serialize( stream, pset );
                            bArray = stream.ToArray();
                        }
                        else
                        {
                            MemoryStream stream = new MemoryStream();
                            BinaryWriter writer = new BinaryWriter( stream, Encoding.Unicode );
                            writer.Write( pset.ToXml().ToString() );
                            writer.Flush();

                            stream.Position = 2;
                            int countBytes = (int)stream.Length - 2;
                            bArray = new byte[countBytes];
                            stream.Read( bArray, 0, bArray.Length );
                        }

                        ((DatabaseEntry)list[i]).binary = bArray;
                    }
                    catch (Exception)
                    {
                        Console.WriteLine( "Error converting entry");
                    }
                }
            }

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

            if (inFormat.Equals( "XMLASCII" ) || inFormat.Equals( "XML" ))
            {
                permSet.FromXml( new Parser( inData, Tokenizer.ByteTokenEncoding.ByteTokens ).GetTopElement() );
            }
            else if (inFormat.Equals( "XMLUNICODE" ))
            {
                permSet.FromXml( new Parser( inData, Tokenizer.ByteTokenEncoding.UnicodeTokens ).GetTopElement() );
            }
            else if (inFormat.Equals( "BINARY" ))
            {
                permSet.DecodeUsingSerialization( inData );
            }
            else
            {
                return null;
            }
            
            if (outFormat.Equals( "XMLASCII" ) || outFormat.Equals( "XML" ))
            {
                MemoryStream ms = new MemoryStream();
                StreamWriter writer = new StreamWriter( ms, Encoding.ASCII );
                writer.Write( permSet.ToXml().ToString() );
                writer.Flush();
                return ms.ToArray();
            }
            else if (outFormat.Equals( "XMLUNICODE" ))
            {
                MemoryStream ms = new MemoryStream();
                StreamWriter writer = new StreamWriter( ms, Encoding.Unicode );
                writer.Write( permSet.ToXml().ToString() );
                writer.Flush();

                ms.Position = 2;
                int countBytes = (int)ms.Length - 2;
                byte[] retval = new byte[countBytes];
                ms.Read( retval, 0, retval.Length );
                return retval;
            }
            else if (outFormat.Equals( "BINARY" ))
            {
                return permSet.EncodeUsingSerialization();
            }
            else
            {
                return null;
            }
        }
Example #19
0
        private static PermissionSet GetPermsFromSpecTree(SecurityElement et)
        {
            BCLDebug.Assert(et != null, "et != null");
            
            SecurityElement el, ec;
            
            if (et.Tag.Equals(s_sPermSpecTag) && et.Children != null)
                ec = (SecurityElement)et.Children[0];
            else if (et.Tag.Equals(s_str_PermissionSet))
                ec = et;
            else
                return null;
            
            if (ec == null)
                return null;

            // All of the next bit is a hack to support capability xml until we're
            // sure the compilers don't use it anymore.
            
            if (ec.Tag.Equals( s_sCapRefTag ))
                el = ec;
            else
                el = ec.SearchForChildByTag(s_sCapRefTag);
                
            if (el != null)
            {
            
                SecurityElement eGUID = el.SearchForChildByTag("GUID");
            
                if (eGUID != null)
                {
                    if (eGUID.Text.Equals("{9653abdf-7db7-11d2-b2eb-00a0c9b4694e}"))
                    {
                        return new PermissionSet( false );
                    }
                    else if (eGUID.Text.Equals("{9653abde-7db7-11d2-b2eb-00a0c9b4694e}"))
                    {
                        return new PermissionSet( true );
                    }
                    else
                    {
                        return new PermissionSet( false );
                    }
                }
                
                return new PermissionSet( false );
            }
            
            if (ec.Tag.Equals( s_str_PermissionSet ))
                el = ec;
            else
                el = ec.SearchForChildByTag(s_str_PermissionSet);
                
            if (el != null)
            {
                PermissionSet permSet = new PermissionSet(false);
                permSet.FromXml(el);
                return permSet;
            }
    
            return null;
        }
Example #20
0
     internal static void AlterBinaryHandler( String[] args )
     {
         if (args[0].Equals( "__internal_usage__" ))
         {
             Console.WriteLine( "SecDBEdit -alterbinary <database_file> <entry_num> <xml_file>\n    Change the Binary at <entry_num> to be what's in <xml_file>" );
             return;
         }
         
         if (args.Length < 4)
         {
             Error( "-alterbinary", "Not enough arguments", -1 );
         }
     
         SecurityElement e = null;
         
         try
         {
             e = GetElementFromFile( args[3] );
         }
         catch (Exception)
         {
             Error( "-alterbinary", "Unable to open and/or parse XML file - " + args[3], -1 );
         }
         
         ArrayList list = null;
 
         try
         {
             list = LoadDatabase( args[1] );
         }
         catch (Exception exc)
         {
             Error( "-alterbinary", exc.Message, -1 );
         }
         
         int index = 0;
         
         try
         {
             index = Int32.Parse( args[2] );
         }
         catch (Exception)
         {
             Error( "-alterbinary", "Invalid index - not a number", -1 );
         }
         
         if (index < 1 || index > list.Count)
             Error( "-alterbinary", "Invalid index - out of range", -1 );
         
         MemoryStream stream = new MemoryStream();
         PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);
         permSet.FromXml( e );
         
         
         BinaryFormatter formatter = new BinaryFormatter();
         formatter.Serialize( stream, permSet );
         
         ((DatabaseEntry)list[index - 1]).binary = stream.ToArray();
 
         try
         {
             SaveDatabase( args[1], list );
         }
         catch (Exception)
         {
             Error( "-alterbinary", "Error saving database", -1 );
         }
     }
Example #21
0
		public void FromXml (SecurityElement el) 
		{
			if (el == null)
				throw new ArgumentNullException ("el");
			if (el.Tag != tagName) {
				string msg = String.Format ("Invalid tag {0} expected {1}", el.Tag, tagName);
				throw new ArgumentException (msg, "el");
			}
			_list.Clear ();
			if (el.Children != null) {
				foreach (SecurityElement child in el.Children) {
					PermissionSet ps = new PermissionSet (PermissionState.None);
					ps.FromXml (child);
					_list.Add (ps);
				}
			}
		}
Example #22
0
        internal static void UpdateHandler( String[] args )
        {
            if (args[0].Equals( "__internal_usage__" ))
            {
                Console.WriteLine( "SecDBEdit -update <file>\n    Add translations for database entries with missing binary values" );
                return;
            }
            
            if (args.Length < 2)
            {
                Error( "-update", "Not enough arguments", -1 );
            }
            
            ArrayList list = null;
            
            try
            {
                list = LoadDatabase( args[1] );
            }
            catch (Exception e)
            {
                Error( "-update", "Failed during load - " + e.Message, -1 );
            }
            
            for (int i = 0; i < list.Count; ++i)
            {
                if ((((DatabaseEntry)list[i]).xml != null) && (((DatabaseEntry)list[i]).binary == null))
                {
                    try
                    {
                        Console.WriteLine( "Adding binary value for entry #" + (i+1) + ":" );
                        PermissionSet pset;
                        if (IsSecAttr( ((DatabaseEntry)list[i]).xml))
                        {
                            pset = SecAttrToPermSet( ((DatabaseEntry)list[i]).xml );
                            Console.WriteLine( pset.ToString() );
                        }
                        else
                        {
                            SecurityElement elem = GetElementFromUbyte( ((DatabaseEntry)list[i]).xml );
                            Console.WriteLine( elem.ToString() );
                            pset = new PermissionSet( PermissionState.None );
                            pset.FromXml( elem );
                        }
                        MemoryStream stream = new MemoryStream();
                        BinaryFormatter formatter = new BinaryFormatter();
                        formatter.Serialize( stream, pset );
                        ((DatabaseEntry)list[i]).binary = stream.ToArray();
                        
                    }
                    catch (Exception)
                    {
                        Console.WriteLine( "Error converting entry");
                    }
                }
            }

            try
            {
                SaveDatabase( args[1], list );
            }
            catch (Exception)
            {
                Error( "-update", "Error saving database", -1 );
            }
        }
		public void FromXml_PermissionOutsideCorlib ()
		{
			SecurityElement child = new SecurityElement ("IPermission");
			child.AddAttribute ("class", "PrintingPermission");	// System.Drawing
			child.AddAttribute ("version", "1");
			child.AddAttribute ("Level", "DefaultPrinting");

			SecurityElement se = new SecurityElement ("PermissionSet");
			se.AddAttribute ("class", "PermissionSet");
			se.AddAttribute ("version", "1");
			se.AddChild (child);

			PermissionSet ps = new PermissionSet (PermissionState.None);
			ps.FromXml (se);
		}
Example #24
0
		// FIXME little documentation in Fx 2.0 beta 1
		public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat) 
		{
			if (inFormat == null)
				throw new ArgumentNullException ("inFormat");
			if (outFormat == null)
				throw new ArgumentNullException ("outFormat");
			if (inData == null)
				return null;

			if (inFormat == outFormat)
				return inData;

			PermissionSet ps = null;

			if (inFormat == "BINARY") {
				if (outFormat.StartsWith ("XML")) {
					using (MemoryStream ms = new MemoryStream (inData)) {
						BinaryFormatter formatter = new BinaryFormatter ();
						ps = (PermissionSet) formatter.Deserialize (ms);
						ms.Close ();
					}
					string xml = ps.ToString ();
					switch (outFormat) {
						case "XML":
						case "XMLASCII":
							return Encoding.ASCII.GetBytes (xml);
						case "XMLUNICODE":
							return Encoding.Unicode.GetBytes (xml);
					}
				}
			}
			else if (inFormat.StartsWith ("XML")) {
				if (outFormat == "BINARY") {
					string xml = null;
					switch (inFormat) {
						case "XML":
						case "XMLASCII":
							xml = Encoding.ASCII.GetString (inData);
							break;
						case "XMLUNICODE":
							xml = Encoding.Unicode.GetString (inData);
							break;
					}
					if (xml != null) {
						ps = new PermissionSet (PermissionState.None);
						ps.FromXml (SecurityElement.FromString (xml));

						MemoryStream ms = new MemoryStream ();
						BinaryFormatter formatter = new BinaryFormatter ();
						formatter.Serialize (ms, ps);
						ms.Close ();
						return ms.ToArray ();
					}
				}
				else if (outFormat.StartsWith ("XML")) {
					string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
					throw new XmlSyntaxException (msg);
				}
			}
			else {
				// unknown inFormat, returns null
				return null;
			}
			// unknown outFormat, throw
			throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
		}
        [System.Security.SecurityCritical]  // auto-generated
        private static Object Deserialize(byte[] blob)
        {
            if (blob == null)
                return null;

            if (blob[0] == 0)
            {
                Parser parser = new Parser( blob, Tokenizer.ByteTokenEncoding.UTF8Tokens, 1 );
                SecurityElement root = parser.GetTopElement();
                if (root.Tag.Equals( "IPermission" ) || root.Tag.Equals( "Permission" ))
                {
                    IPermission ip = System.Security.Util.XMLUtil.CreatePermission( root, PermissionState.None, false );

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

                    ip.FromXml( root );

                    return ip;
                }
                else if (root.Tag.Equals( "PermissionSet" ))
                {
                    PermissionSet permissionSet = new PermissionSet();

                    permissionSet.FromXml( root, false, false );

                    return permissionSet;
                }
                else if (root.Tag.Equals( "PermissionToken" ))
                {
                    PermissionToken pToken = new PermissionToken();

                    pToken.FromXml( root );

                    return pToken;
                }
                else
                {
                    return null;
                }

            }
            else
            {
                Object obj = null;
                using(MemoryStream stream = new MemoryStream( blob, 1, blob.Length - 1 )) {
                    obj = CrossAppDomainSerializer.DeserializeObject(stream);
                }

                Contract.Assert( !(obj is IPermission), "IPermission should be xml deserialized" );
                Contract.Assert( !(obj is PermissionSet), "PermissionSet should be xml deserialized" );

                return obj;
            }
        }
Example #26
0
 private static object Deserialize(byte[] blob)
 {
     if (blob == null)
     {
         return null;
     }
     if (blob[0] == 0)
     {
         SecurityElement topElement = new Parser(blob, Tokenizer.ByteTokenEncoding.UTF8Tokens, 1).GetTopElement();
         if (topElement.Tag.Equals("IPermission") || topElement.Tag.Equals("Permission"))
         {
             IPermission permission = XMLUtil.CreatePermission(topElement, PermissionState.None, false);
             if (permission == null)
             {
                 return null;
             }
             permission.FromXml(topElement);
             return permission;
         }
         if (topElement.Tag.Equals("PermissionSet"))
         {
             PermissionSet set = new PermissionSet();
             set.FromXml(topElement, false, false);
             return set;
         }
         if (topElement.Tag.Equals("PermissionToken"))
         {
             PermissionToken token = new PermissionToken();
             token.FromXml(topElement);
             return token;
         }
         return null;
     }
     using (MemoryStream stream = new MemoryStream(blob, 1, blob.Length - 1))
     {
         return CrossAppDomainSerializer.DeserializeObject(stream);
     }
 }
Example #27
0
        // Convert a permission set from one format to another.
        public static byte[] ConvertPermissionSet
            (String inFormat, byte[] inData, String outFormat)
        {
            // Validate the parameters.
            if (inFormat == null)
            {
                throw new ArgumentNullException("inFormat");
            }
            if (inData == null)
            {
                throw new ArgumentNullException("inData");
            }
            if (outFormat == null)
            {
                throw new ArgumentNullException("outFormat");
            }

            // Convert the input data into a permission set.
            PermissionSet   permSet;
            SecurityElement e;

            switch (inFormat.ToLower(CultureInfo.InvariantCulture))
            {
            case "xml":
            case "xmlascii":
            {
                permSet = new PermissionSet(PermissionState.None);
                e       = (new MiniXml(Encoding.UTF8.GetString(inData)))
                          .Parse();
                permSet.FromXml(e);
            }
            break;

            case "xmlunicode":
            {
                permSet = new PermissionSet(PermissionState.None);
                e       = (new MiniXml(Encoding.Unicode.GetString(inData)))
                          .Parse();
                permSet.FromXml(e);
            }
            break;

                                #if CONFIG_SERIALIZATION
            case "binary":
            {
                MemoryStream inStream = new MemoryStream(inData);
                permSet = (PermissionSet)
                          ((new BinaryFormatter()).Deserialize(inStream));
            }
            break;
                                #endif

            default: return(null);
            }

            // Convert the output data into a permission set.
            switch (outFormat.ToLower(CultureInfo.InvariantCulture))
            {
            case "xml":
            case "xmlascii":
            {
                e = permSet.ToXml();
                return(Encoding.UTF8.GetBytes(e.ToString()));
            }
            // Not reached.

            case "xmlunicode":
            {
                e = permSet.ToXml();
                return(Encoding.Unicode.GetBytes(e.ToString()));
            }
                // Not reached.

                                #if CONFIG_SERIALIZATION
            case "binary":
            {
                MemoryStream outStream = new MemoryStream();
                (new BinaryFormatter()).Serialize(outStream, permSet);
                return(outStream.ToArray());
            }
                // Not reached.
                                #endif
            }
            return(null);
        }
		public void FromXmlInvalidPermission () 
		{
			PermissionSet ps = new PermissionSet (PermissionState.None);
			SecurityElement se = ps.ToXml ();
			// can't modify - so we create our own
			SecurityElement se2 = new SecurityElement ("InvalidPermissionSet", se.Text);
			se2.AddAttribute ("class", se.Attribute ("class"));
			se2.AddAttribute ("version", se.Attribute ("version"));
			ps.FromXml (se2);
		}
Example #29
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;
        }
		public void FromXml_PermissionWithoutNamespace ()
		{
			SecurityElement child = new SecurityElement ("IPermission");
			child.AddAttribute ("class", "EnvironmentPermission");
			child.AddAttribute ("version", "1");
			child.AddAttribute ("Read", "USERNAME");

			SecurityElement se = new SecurityElement ("PermissionSet");
			se.AddAttribute ("class", "PermissionSet");
			se.AddAttribute ("version", "1");
			se.AddChild (child);

			PermissionSet ps = new PermissionSet (PermissionState.None);
			ps.FromXml (se);
		}
 internal object ToSecurityObject()
 {
     string str;
     if (((str = this.m_strTag) != null) && (str == "PermissionSet"))
     {
         PermissionSet set = new PermissionSet(PermissionState.None);
         set.FromXml(this);
         return set;
     }
     return this.ToPermission(false);
 }
		public void FromXml_WithPermissionWithoutClass ()
		{
			SecurityElement child = new SecurityElement ("IPermission");
			child.AddAttribute ("version", "1");

			SecurityElement se = new SecurityElement ("PermissionSet");
			se.AddAttribute ("class", "PermissionSet");
			se.AddAttribute ("version", "1");
			se.AddChild (child);

			PermissionSet ps = new PermissionSet (PermissionState.None);
			ps.FromXml (se);
		}
Example #33
0
        [System.Security.SecurityCritical]  // auto-generated
        internal Object ToSecurityObject()
        {
            switch (m_strTag)
            {
                case "PermissionSet":
                    PermissionSet pset = new PermissionSet(PermissionState.None);
                    pset.FromXml(this);
                    return pset;

                default:
                    return ToPermission(false);
            }
        }
Example #34
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);
		}
	// Convert a permission set from one format to another.
	public static byte[] ConvertPermissionSet
				(String inFormat, byte[] inData, String outFormat)
			{
				// Validate the parameters.
				if(inFormat == null)
				{
					throw new ArgumentNullException("inFormat");
				}
				if(inData == null)
				{
					throw new ArgumentNullException("inData");
				}
				if(outFormat == null)
				{
					throw new ArgumentNullException("outFormat");
				}

				// Convert the input data into a permission set.
				PermissionSet permSet;
				SecurityElement e;
				switch(inFormat.ToLower(CultureInfo.InvariantCulture))
				{
					case "xml": case "xmlascii":
					{
						permSet = new PermissionSet(PermissionState.None);
						e = (new MiniXml(Encoding.UTF8.GetString(inData)))
								.Parse();
						permSet.FromXml(e);
					}
					break;

					case "xmlunicode":
					{
						permSet = new PermissionSet(PermissionState.None);
						e = (new MiniXml(Encoding.Unicode.GetString(inData)))
								.Parse();
						permSet.FromXml(e);
					}
					break;

				#if CONFIG_SERIALIZATION
					case "binary":
					{
						MemoryStream inStream = new MemoryStream(inData);
						permSet = (PermissionSet)
							((new BinaryFormatter()).Deserialize(inStream));
					}
					break;
				#endif

					default: return null;
				}

				// Convert the output data into a permission set.
				switch(outFormat.ToLower(CultureInfo.InvariantCulture))
				{
					case "xml": case "xmlascii":
					{
						e = permSet.ToXml();
						return Encoding.UTF8.GetBytes(e.ToString());
					}
					// Not reached.

					case "xmlunicode":
					{
						e = permSet.ToXml();
						return Encoding.Unicode.GetBytes(e.ToString());
					}
					// Not reached.

				#if CONFIG_SERIALIZATION
					case "binary":
					{
						MemoryStream outStream = new MemoryStream();
						(new BinaryFormatter()).Serialize(outStream, permSet);
						return outStream.ToArray();
					}
					// Not reached.
				#endif
				}
				return null;
			}