public ZoneIdentityPermission(PermissionState state) { // false == do not allow Unrestricted for Identity Permissions CheckPermissionState(state, false); // default values zone = SecurityZone.NoZone; }
private static void VerifyZone(SecurityZone zone) { if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted) { throw new ArgumentException(Environment.GetResourceString("Argument_IllegalZone")); } }
/// <include file='doc\Zone.uex' path='docs/doc[@for="Zone.Zone"]/*' /> public Zone(SecurityZone zone) { if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted) throw new ArgumentException( Environment.GetResourceString( "Argument_IllegalZone" ) ); m_zone = zone; }
// Implement the ISecurityPolicyEncodable interface. public void FromXml(SecurityElement et, PolicyLevel level) { if (et == null) { throw new ArgumentNullException("et"); } if (et.Tag != "IMembershipCondition") { throw new ArgumentException(_("Security_PolicyName")); } if (et.Attribute("version") != "1") { throw new ArgumentException(_("Security_PolicyVersion")); } String value = et.Attribute("Zone"); if (value != null) { zone = (SecurityZone) Enum.Parse(typeof(SecurityZone), value); } else { throw new ArgumentException(_("Arg_SecurityZone")); } }
public override IPermission Union(IPermission target) { if (target == null) { return(Copy()); } else if (!(target is ZoneIdentityPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } SecurityZone otherZone = ((ZoneIdentityPermission)target).zone; if (zone == otherZone || otherZone == SecurityZone.NoZone) { return(Copy()); } else if (zone == SecurityZone.NoZone) { return(target.Copy()); } else { return(null); } }
private static XmlElement GetCurrentCLRPermissions(string targetZone) { string str = string.Empty; SecurityZone noZone = SecurityZone.NoZone; string str2 = targetZone; if (str2 != null) { if (!(str2 == "LocalIntranet")) { if (str2 == "Internet") { noZone = SecurityZone.Internet; goto Label_0044; } } else { noZone = SecurityZone.Intranet; goto Label_0044; } } throw new ArgumentException(string.Empty, "targetZone"); Label_0044 :; Evidence evidence = new Evidence(new EvidenceBase[] { new Zone(noZone), new ActivationArguments(new System.ApplicationIdentity("")) }, null); str = SecurityManager.GetStandardSandbox(evidence).ToString(); if (!string.IsNullOrEmpty(str)) { XmlDocument document = new XmlDocument(); document.LoadXml(str); return(document.DocumentElement); } return(null); }
public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, object demanded, IPermission permThatFailed, Evidence evidence) : base(message) { PermissionSet.s_fullTrust.Assert(); this.SetErrorCode(-2146233078); this.Action = action; if (permThatFailed != null) { this.m_typeOfPermissionThatFailed = permThatFailed.GetType(); } this.FirstPermissionThatFailed = permThatFailed; this.Demanded = demanded; this.m_granted = grant == null ? "" : grant.ToXml().ToString(); this.m_refused = refused == null ? "" : refused.ToXml().ToString(); this.m_denied = ""; this.m_permitOnly = ""; this.m_assemblyName = assemblyName; this.Method = method; this.m_url = ""; this.m_zone = SecurityZone.NoZone; if (evidence != null) { System.Security.Policy.Url hostEvidence1 = evidence.GetHostEvidence <System.Security.Policy.Url>(); if (hostEvidence1 != null) { this.m_url = hostEvidence1.GetURLString().ToString(); } System.Security.Policy.Zone hostEvidence2 = evidence.GetHostEvidence <System.Security.Policy.Zone>(); if (hostEvidence2 != null) { this.m_zone = hostEvidence2.SecurityZone; } } this.m_debugString = this.ToString(true, false); }
public async Task InvokeAsync( Expression <Action <CancellationToken> > invocation, CancellationToken ct = new CancellationToken(), TimeSpan?cancellationTimeout = null, ForcedCancellationMode forcedCancellationMode = ForcedCancellationMode.CleanupAfterCancellation, SecurityZone securityZone = SecurityZone.MyComputer, WorkerProcessRef workerProcessRef = null ) { if (this.disposed) { throw new ObjectDisposedException("This instance has been disposed."); } try { this.standbyTask.Cancel(); var nextWorker = await this.ActivateWorker(ct); await nextWorker .InvokeRemotely(invocation, ct, cancellationTimeout.GetValueOrDefault(this.defaultCancellationTimeout), forcedCancellationMode, securityZone, workerProcessRef); } finally { this.standbyTask.Reset(); } }
private ZoneIdentityPermission BasicTestZone (SecurityZone zone, bool special) { ZoneIdentityPermission zip = new ZoneIdentityPermission (zone); Assert.AreEqual (zone, zip.SecurityZone, "SecurityZone"); ZoneIdentityPermission copy = (ZoneIdentityPermission) zip.Copy (); Assert.IsTrue (Same (zip, copy), "Equals-Copy"); Assert.IsTrue (zip.IsSubsetOf (copy), "IsSubset-1"); Assert.IsTrue (copy.IsSubsetOf (zip), "IsSubset-2"); if (special) { Assert.IsFalse (zip.IsSubsetOf (null), "IsSubset-Null"); } IPermission intersect = zip.Intersect (copy); if (special) { Assert.IsTrue (intersect.IsSubsetOf (zip), "IsSubset-3"); Assert.IsFalse (Object.ReferenceEquals (zip, intersect), "!ReferenceEquals1"); Assert.IsTrue (intersect.IsSubsetOf (copy), "IsSubset-4"); Assert.IsFalse (Object.ReferenceEquals (copy, intersect), "!ReferenceEquals2"); } Assert.IsNull (zip.Intersect (null), "Intersect with null"); intersect = zip.Intersect (new ZoneIdentityPermission (PermissionState.None)); Assert.IsNull (intersect, "Intersect with PS.None"); // note: can't be tested with PermissionState.Unrestricted // XML roundtrip SecurityElement se = zip.ToXml (); copy.FromXml (se); Assert.IsTrue (Same (zip, copy), "Equals-Xml"); return zip; }
/// <summary> /// Gets the referer to set as a header on the HTTP request. /// We do not set the referer if we are navigating to a /// differnet security zone or to a different Uri scheme. /// </summary> internal static string GetReferer(Uri destinationUri) { string referer = null; Uri sourceUri = MS.Internal.AppModel.SiteOfOriginContainer.BrowserSource; if (sourceUri != null) { SecurityZone sourceZone = MS.Internal.AppModel.CustomCredentialPolicy.MapUrlToZone(sourceUri); SecurityZone targetZone = MS.Internal.AppModel.CustomCredentialPolicy.MapUrlToZone(destinationUri); // We don't send any referer when crossing zone if (sourceZone == targetZone) { // We don't send any referer when going cross-scheme if (SecurityHelper.AreStringTypesEqual(sourceUri.Scheme, destinationUri.Scheme)) { // HTTPHeader requires the referer uri to be escaped. referer = sourceUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped); } } } return(referer); }
[System.Security.SecuritySafeCritical] // auto-generated public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); Action = action; if (permThatFailed != null) { m_typeOfPermissionThatFailed = permThatFailed.GetType(); } FirstPermissionThatFailed = permThatFailed; Demanded = demanded; m_granted = (grant == null ? "" : grant.ToXml().ToString()); m_refused = (refused == null ? "" : refused.ToXml().ToString()); m_denied = ""; m_permitOnly = ""; m_assemblyName = assemblyName; Method = method; m_url = ""; m_zone = SecurityZone.NoZone; if (evidence != null) { Url url = evidence.GetHostEvidence <Url>(); if (url != null) { m_url = url.GetURLString().ToString(); } Zone zone = evidence.GetHostEvidence <Zone>(); if (zone != null) { m_zone = zone.SecurityZone; } } m_debugString = this.ToString(true, false); }
public ZoneIdentityPermission (PermissionState state) { // false == do not allow Unrestricted for Identity Permissions CheckPermissionState (state, false); // default values zone = SecurityZone.NoZone; }
private void ResolveEvidenceHost(SecurityZone zone, bool unrestricted, bool empty) { string prefix = zone.ToString() + "-"; Evidence e = new Evidence(); e.AddHost(new Zone(zone)); PermissionSet ps = SecurityManager.ResolvePolicy(e); // as 2.0 use Unrestricted for Identity permissions they have no need to be // kept in resolved permission set #if NET_2_0 Assert.IsTrue((unrestricted || (ps.Count > 0)), prefix + "Count"); #else Assert.IsTrue((ps.Count > 0), prefix + "Count"); #endif Assert.AreEqual(empty, ps.IsEmpty(), prefix + "IsEmpty"); Assert.AreEqual(unrestricted, ps.IsUnrestricted(), prefix + "IsUnrestricted"); #if NET_2_0 if (unrestricted) { Assert.IsNull(ps.GetPermission(typeof(ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)"); } else { Assert.IsNotNull(ps.GetPermission(typeof(ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)"); } #else Assert.IsNotNull(ps.GetPermission(typeof(ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)"); #endif }
private void ParseZone() { lock (this) { if (m_element == null) { return; } String eZone = m_element.Attribute("Zone"); m_zone = SecurityZone.NoZone; if (eZone != null) { m_zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), eZone); } else { throw new ArgumentException(Environment.GetResourceString("Argument_ZoneCannotBeNull")); } VerifyZone(m_zone); m_element = null; } }
private ZoneMembershipCondition BasicTest(SecurityZone zone) { ZoneMembershipCondition zmc = new ZoneMembershipCondition(zone); Assert.AreEqual(zone, zmc.SecurityZone, "SecurityZone"); Assert.IsFalse(zmc.Check(null), "Check(null)"); Assert.IsFalse(zmc.Check(allEmpty), "Check(empty)"); Assert.IsFalse(zmc.Check(hostOther), "Check(hostOther)"); Assert.IsFalse(zmc.Check(assemblyOther), "Check(assemblyOther)"); ZoneMembershipCondition copy = (ZoneMembershipCondition)zmc.Copy(); Assert.IsTrue(zmc.Equals(copy), "Equals-1"); Assert.IsTrue(copy.Equals(zmc), "Equals-2"); Assert.IsFalse(Object.ReferenceEquals(zmc, copy), "!ReferenceEquals"); Assert.IsFalse(zmc.Equals(null), "Equals-3"); Assert.IsFalse(zmc.Equals(wrongEvidence), "Equals-4"); SecurityElement se = zmc.ToXml(); copy.FromXml(se); Assert.IsTrue(zmc.Equals(copy), "Equals-5"); Assert.AreEqual(se.ToString(), zmc.ToXml(null).ToString(), "Equals-6"); Assert.IsTrue(zmc.ToString().StartsWith("Zone - "), "ToString-1"); Assert.IsTrue(zmc.ToString().EndsWith(zmc.SecurityZone.ToString()), "ToString-2"); #if NET_2_0 Assert.AreEqual(zmc.SecurityZone.GetHashCode(), zmc.GetHashCode(), "GetHashCode"); #endif return(zmc); // for further tests }
private void GenerateLocationEvidence() { if (!m_generatedLocationEvidence) { SecurityZone securityZone = SecurityZone.NoZone; string url = null; GetLocationEvidence(m_peFile, out securityZone, JitHelpers.GetStringHandleOnStack(ref url)); if (securityZone != SecurityZone.NoZone) { m_zoneEvidence = new Zone(securityZone); } if (!String.IsNullOrEmpty(url)) { m_urlEvidence = new Url(url, true); // We only create site evidence if the URL does not with file: if (!url.StartsWith("file:", StringComparison.OrdinalIgnoreCase)) { m_siteEvidence = Site.CreateFromUrl(url); } } m_generatedLocationEvidence = true; } }
public static SandboxInstance CreateSandbox(string applicationBase, SecurityZone securityZone) { Type typeOfSandbox = typeof(SandboxInstance); AppDomainSetup appDomainSetup = ObjectFactory.GetInstance <AppDomainSetup>(); Evidence evidence = ObjectFactory.GetInstance <Evidence>(); Zone zone = new Zone(securityZone); appDomainSetup.ApplicationBase = applicationBase; evidence.AddHostEvidence(zone); PermissionSet permissionSet = SecurityManager.GetStandardSandbox(evidence); StrongName fullTrustAssembly = typeOfSandbox.Assembly.Evidence.GetHostEvidence <StrongName>(); AppDomain appDomain = AppDomain.CreateDomain( FrienldyName, evidence, appDomainSetup, permissionSet, fullTrustAssembly); ObjectHandle handle = Activator.CreateInstanceFrom( appDomain, typeOfSandbox.Assembly.ManifestModule.FullyQualifiedName, typeOfSandbox.FullName); return(handle.Unwrap() as SandboxInstance); }
// Constructor. public ZoneIdentityPermission(PermissionState state) { if (state != PermissionState.None) { throw new ArgumentException(_("Arg_PermissionState")); } zone = SecurityZone.NoZone; }
//------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ private static void VerifyZone(SecurityZone zone) { if (zone < SecurityZone.MyComputer || zone > SecurityZone.Untrusted) { throw new ArgumentException(Environment.GetResourceString("Argument_IllegalZone")); } Contract.EndContractBlock(); }
// Constructor. public ZoneIdentityPermission(PermissionState state) { if(state != PermissionState.None) { throw new ArgumentException(_("Arg_PermissionState")); } zone = SecurityZone.NoZone; }
private void OnSerialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone | StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = null; m_zone = SecurityZone.NoZone; } }
/// <summary>Initializes a new instance of the <see cref="T:System.Security.Policy.Zone" /> class with the zone from which a code assembly originates.</summary> /// <param name="zone">The zone of origin for the associated code assembly. </param> /// <exception cref="T:System.ArgumentException">The <paramref name="zone" /> parameter is not a valid <see cref="T:System.Security.SecurityZone" />. </exception> // Token: 0x06002A7B RID: 10875 RVA: 0x0009DF3D File Offset: 0x0009C13D public Zone(SecurityZone zone) { if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted) { throw new ArgumentException(Environment.GetResourceString("Argument_IllegalZone")); } this.m_zone = zone; }
private void OnSerializing(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone | StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case m_zone = SecurityZone; } }
private static void RunScenario(SecurityZone zone, bool fullyTrustEventSource, bool grantUnmanagedCodePermission) { Console.Write("Running scenario for zone '{0}', fully trusted EventSource {1}, unmanaged permission {2}: ", zone, fullyTrustEventSource, grantUnmanagedCodePermission); var evidence = new Evidence(); evidence.AddHostEvidence(new Zone(zone)); var permissionSet = SecurityManager.GetStandardSandbox(evidence); if (!permissionSet.IsUnrestricted() && grantUnmanagedCodePermission) { permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); } var eventSourceAssemblyName = typeof(EventSource).Assembly.GetName(); var fullyTrustedAssemblies = fullyTrustEventSource ? new StrongName[] { new StrongName(new StrongNamePublicKeyBlob(eventSourceAssemblyName.GetPublicKey()), eventSourceAssemblyName.Name, eventSourceAssemblyName.Version) } : new StrongName[0]; var info = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; info.ApplicationTrust = new ApplicationTrust(permissionSet, fullyTrustedAssemblies); var appDomain = AppDomain.CreateDomain( "partial trust", evidence, info); try { var tester = (LttADEventSourceTester)appDomain .CreateInstanceAndUnwrap( typeof(LttADEventSourceTester).Assembly.GetName().Name, typeof(LttADEventSourceTester).FullName); tester.IsEventSourceAssmFullyTrusted = fullyTrustEventSource; tester.DoStuff(1); tester.DoStuff(2); tester.DoStuff(3); Assert.IsTrue(tester.IsStateValid, "EventSource ConstructionException as expected"); Console.WriteLine("SUCCESS"); Console.WriteLine(); } finally { AppDomain.Unload(appDomain); } Console.WriteLine("=================================================================="); Console.WriteLine(); }
public ZoneMembershipCondition(SecurityZone zone) { if(zone < SecurityZone.MyComputer || zone > SecurityZone.Untrusted) { throw new ArgumentException(_("Arg_SecurityZone")); } this.zone = zone; }
private void OnSerialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone | StreamingContextStates.CrossAppDomain)) == (StreamingContextStates)0) { return; } this.m_serializedPermission = (string)null; this.m_zone = SecurityZone.NoZone; }
public ZoneMembershipCondition(SecurityZone zone) { if (zone < SecurityZone.MyComputer || zone > SecurityZone.Untrusted) { throw new ArgumentException(_("Arg_SecurityZone")); } this.zone = zone; }
// Constructor. public Zone(SecurityZone zone) { if (((int)zone) < ((int)(SecurityZone.NoZone)) || ((int)zone) > ((int)(SecurityZone.Untrusted))) { throw new ArgumentException(_("Arg_SecurityZone")); } this.zone = zone; }
private void OnSerializing(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone | StreamingContextStates.CrossAppDomain)) == (StreamingContextStates)0) { return; } this.m_serializedPermission = this.ToXml().ToString(); this.m_zone = this.SecurityZone; }
// Constructor. public Zone(SecurityZone zone) { if(((int)zone) < ((int)(SecurityZone.NoZone)) || ((int)zone) > ((int)(SecurityZone.Untrusted))) { throw new ArgumentException(_("Arg_SecurityZone")); } this.zone = zone; }
private Zone(Zone zone) { Contract.Assert(zone != null); #if FEATURE_CAS_POLICY m_url = zone.m_url; #endif // FEATURE_CAS_POLICY m_zone = zone.m_zone; }
/// <summary>Initializes a new instance of the <see cref="T:System.Security.Policy.Zone" /> class with the zone from which a code assembly originates.</summary> /// <param name="zone">The zone of origin for the associated code assembly. </param> /// <exception cref="T:System.ArgumentException">The <paramref name="zone" /> parameter is not a valid <see cref="T:System.Security.SecurityZone" />. </exception> public Zone(SecurityZone zone) { if (!Enum.IsDefined(typeof(SecurityZone), zone)) { string message = string.Format(Locale.GetText("Invalid zone {0}."), zone); throw new ArgumentException(message, "zone"); } this.zone = zone; }
public void Resolve_InternetUnrestricted() { SecurityZone z = SecurityZone.Internet; Resolve_Zone_Unrestricted_Attribute(z, PolicyStatementAttribute.Nothing); Resolve_Zone_Unrestricted_Attribute(z, PolicyStatementAttribute.Exclusive); Resolve_Zone_Unrestricted_Attribute(z, PolicyStatementAttribute.LevelFinal); Resolve_Zone_Unrestricted_Attribute(z, PolicyStatementAttribute.All); }
/// <summary> /// Map the file to SecurityZone. /// </summary> /// <remarks> /// The algorithm is as follows: /// /// 1. Alternate data stream "Zone.Identifier" is checked first. If this alternate data stream has content, then the content is parsed to determine the SecurityZone. /// 2. If the alternate data stream "Zone.Identifier" doesn't exist, or its content is not expected, then the file path will be analyzed to determine the SecurityZone. /// /// For #1, the parsing rules are observed as follows: /// A. Read content of the data stream line by line. Each line is trimmed. /// B. Try to match the current line with '^\[ZoneTransfer\]'. /// - if matching, then do step (#C) starting from the next line /// - if not matching, then continue to do step (#B) with the next line. /// C. Try to match the current line with '^ZoneId\s*=\s*(.*)' /// - if matching, check if the ZoneId is valid. Then return the corresponding SecurityZone if the 'ZoneId' is valid, or 'NoZone' if invalid. /// - if not matching, then continue to do step (#C) with the next line. /// D. Reach EOF, then return 'NoZone'. /// After #1, if the returned SecurityZone is 'NoZone', then proceed with #2. Otherwise, return it as the mapping result. /// /// For #2, the analysis rules are observed as follows: /// A. If the path is a UNC path, then /// - if the host name of the UNC path is IP address, then mapping it to "Internet" zone. /// - if the host name of the UNC path has dot (.) in it, then mapping it to "internet" zone. /// - otherwise, mapping it to "intranet" zone. /// B. If the path is not UNC path, then get the root drive, /// - if the drive is CDRom, mapping it to "Untrusted" zone /// - if the drive is Network, mapping it to "Intranet" zone /// - otherwise, mapping it to "MyComputer" zone. /// /// The above algorithm has two changes comparing to the behavior of "Zone.CreateFromUrl" I observed: /// (1) If a file downloaded from internet (ZoneId=3) is not on the local machine, "Zone.CreateFromUrl" won't respect the MOTW. /// I think it makes more sense for powershell to always check the MOTW first, even for files not on local box. /// (2) When it's a UNC path and is actually a loopback (\\127.0.0.1\c$\test.txt), "Zone.CreateFromUrl" returns "Internet", but /// the above algorithm changes it to be "MyComputer" because it's actually the same computer. /// </remarks> private static SecurityZone MapSecurityZone(string filePath) { // WSL introduces a new filesystem path to access the Linux filesystem from Windows, like '\\wsl$\ubuntu'. // If the given file path is such a special case, we consider it's in 'MyComputer' zone. if (filePath.StartsWith(Utils.WslRootPath, StringComparison.OrdinalIgnoreCase)) { return(SecurityZone.MyComputer); } SecurityZone reval = ReadFromZoneIdentifierDataStream(filePath); if (reval != SecurityZone.NoZone) { return(reval); } // If it reaches here, then we either couldn't get the ZoneId information, or the ZoneId is invalid. // In this case, we try to determine the SecurityZone by analyzing the file path. Uri uri = new Uri(filePath); if (uri.IsUnc) { if (uri.IsLoopback) { return(SecurityZone.MyComputer); } if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6) { return(SecurityZone.Internet); } // This is also an observation of Zone.CreateFromUrl/Zone.SecurityZone. If the host name // has 'dot' in it, the file will be treated as in Internet security zone. Otherwise, it's // in Intranet security zone. string hostName = uri.Host; return(hostName.Contains('.') ? SecurityZone.Intranet : SecurityZone.Internet); } string root = Path.GetPathRoot(filePath); DriveInfo drive = new DriveInfo(root); switch (drive.DriveType) { case DriveType.NoRootDirectory: case DriveType.Unknown: case DriveType.CDRom: return(SecurityZone.Untrusted); case DriveType.Network: return(SecurityZone.Intranet); default: return(SecurityZone.MyComputer); } }
public Zone (SecurityZone zone) { if (!Enum.IsDefined (typeof (SecurityZone), zone)) { string msg = String.Format (Locale.GetText ("Invalid zone {0}."), zone); throw new ArgumentException (msg, "zone"); } this.zone = zone; }
// returns when invocation is started, but before it returns // end of invocation is signaled via TaskCompletionSourceProxy public void InvokeAsync( InvocationRequest.PortableInvocationRequest invocationRequest, SecurityZone securityZone ) { if (invocationRequest == null) { throw new ArgumentNullException("invocationRequest"); } lock (this.stateLock) { if (!this.isReady) { throw new InvalidOperationException( "Not ready: currently executing another task or cleaning up."); } this.isReady = false; var zoneEvidence = new Evidence(); zoneEvidence.AddHostEvidence(new Zone(securityZone)); var zonePermissions = SecurityManager.GetStandardSandbox(zoneEvidence); var taskDomainName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", invocationRequest.MethodName, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); // ReSharper disable once AssignNullToNotNullAttribute this.activeRunnerDomain = AppDomain.CreateDomain(taskDomainName, AppDomain.CurrentDomain.Evidence, new AppDomainSetup { ApplicationBase = invocationRequest.ApplicationBase, LoaderOptimization = LoaderOptimization.MultiDomainHost }, zonePermissions, typeof(WorkerServer).GetStrongNameOfAssemblyAsArray()); this.activeRunner = (TaskRunner)this.activeRunnerDomain.CreateInstanceFromAndUnwrap( typeof(TaskRunner).Assembly.Location, typeof(TaskRunner).FullName); this.activeRunner.Setup(); this.proxyLifetimeSponsor.Register(this.activeRunner); } Task.Run(() => { // this invocation can fail by to ways: // 1. forced shutdown of appdomain - ignore silently // 2. serialization exception related to type of result - pass to callee try { var result = this.activeRunner.InvokeSynchronously(invocationRequest); this.OnRunnerDone(result); } catch (SerializationException e) { this.OnRunnerDone(new TaskFailedEventArgs(e)); } finally { this.Cleanup(true); } }); Console.WriteLine(string.Format( CultureInfo.InvariantCulture, "{0} Started executing invocation request.", this.serverId)); }
public static Zone CreateFromUrl(string url) { if (url == null) { throw new ArgumentNullException("url"); } SecurityZone z = SecurityZone.NoZone; if (url.Length == 0) { return(new Zone(z)); } Uri uri = null; try { uri = new Uri(url); } catch { return(new Zone(z)); } // TODO: apply zone configuration // this is the only way to use the Trusted and Untrusted zones if (z == SecurityZone.NoZone) { // not part of configuration, the use default mapping if (uri.IsFile) { if (File.Exists(uri.LocalPath)) { z = SecurityZone.MyComputer; } else if (String.Compare("FILE://", 0, url, 0, 7, true, CultureInfo.InvariantCulture) == 0) { z = SecurityZone.Intranet; // non accessible file:// } else { z = SecurityZone.Internet; } } else if (uri.IsLoopback) // e.g. http://localhost/x { z = SecurityZone.Intranet; } else { // all protocols, including unknown ones z = SecurityZone.Internet; } } return(new Zone(z)); }
private void OnSerializing(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case m_zone = SecurityZone; } }
public AppDomain CreateSandboxDomain(string name, string path, SecurityZone zone) { var setup = new AppDomainSetup { ApplicationBase = Common.ApiPath, PrivateBinPath = Path.GetFullPath(path) }; var evidence = new Evidence(); evidence.AddHostEvidence(new Zone(zone)); var permissions = SecurityManager.GetStandardSandbox(evidence); var strongName = typeof(OSAEService).Assembly.Evidence.GetHostEvidence<StrongName>(); return AppDomain.CreateDomain(name, null, setup); }
//------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ /// <include file='doc\ZoneIdentityPermission.uex' path='docs/doc[@for="ZoneIdentityPermission.ZoneIdentityPermission"]/*' /> public ZoneIdentityPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { throw new ArgumentException(Environment.GetResourceString("Argument_UnrestrictedIdentityPermission")); } else if (state == PermissionState.None) { m_zone = SecurityZone.NoZone; } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } }
private void OnDeserialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { // v2.0 and beyond XML case if (m_serializedPermission != null) { FromXml(SecurityElement.FromString(m_serializedPermission)); m_serializedPermission = null; } else //v1.x case where we read the m_zone value { SecurityZone = m_zone; m_zone = SecurityZone.NoZone; } } }
// Convert an XML value into a permissions value. public override void FromXml(SecurityElement esd) { String value; if(esd == null) { throw new ArgumentNullException("esd"); } if(esd.Attribute("version") != "1") { throw new ArgumentException(_("Arg_PermissionVersion")); } value = esd.Attribute("Zone"); if(value != null) { zone = (SecurityZone) Enum.Parse(typeof(SecurityZone), value); } else { zone = SecurityZone.NoZone; } }
protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new ArgumentNullException("info"); } try { this.m_action = (SecurityAction) info.GetValue("Action", typeof(SecurityAction)); this.m_permissionThatFailed = (string) info.GetValueNoThrow("FirstPermissionThatFailed", typeof(string)); this.m_demanded = (string) info.GetValueNoThrow("Demanded", typeof(string)); this.m_granted = (string) info.GetValueNoThrow("GrantedSet", typeof(string)); this.m_refused = (string) info.GetValueNoThrow("RefusedSet", typeof(string)); this.m_denied = (string) info.GetValueNoThrow("Denied", typeof(string)); this.m_permitOnly = (string) info.GetValueNoThrow("PermitOnly", typeof(string)); this.m_assemblyName = (AssemblyName) info.GetValueNoThrow("Assembly", typeof(AssemblyName)); this.m_serializedMethodInfo = (byte[]) info.GetValueNoThrow("Method", typeof(byte[])); this.m_strMethodInfo = (string) info.GetValueNoThrow("Method_String", typeof(string)); this.m_zone = (SecurityZone) info.GetValue("Zone", typeof(SecurityZone)); this.m_url = (string) info.GetValueNoThrow("Url", typeof(string)); } catch { this.m_action = (SecurityAction) 0; this.m_permissionThatFailed = ""; this.m_demanded = ""; this.m_granted = ""; this.m_refused = ""; this.m_denied = ""; this.m_permitOnly = ""; this.m_assemblyName = null; this.m_serializedMethodInfo = null; this.m_strMethodInfo = null; this.m_zone = SecurityZone.NoZone; this.m_url = ""; } }
private void ResolveEvidenceHost (SecurityZone zone, bool unrestricted, bool empty) { string prefix = zone.ToString () + "-"; Evidence e = new Evidence (); e.AddHost (new Zone (zone)); PermissionSet ps = SecurityManager.ResolvePolicy (e); // as 2.0 use Unrestricted for Identity permissions they have no need to be // kept in resolved permission set #if NET_2_0 Assert.IsTrue ((unrestricted || (ps.Count > 0)), prefix + "Count"); #else Assert.IsTrue ((ps.Count > 0), prefix + "Count"); #endif Assert.AreEqual (empty, ps.IsEmpty (), prefix + "IsEmpty"); Assert.AreEqual (unrestricted, ps.IsUnrestricted (), prefix + "IsUnrestricted"); #if NET_2_0 if (unrestricted) Assert.IsNull (ps.GetPermission (typeof (ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)"); else Assert.IsNotNull (ps.GetPermission (typeof (ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)"); #else Assert.IsNotNull (ps.GetPermission (typeof (ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)"); #endif }
private Zone(String url) { m_url = url; m_zone = SecurityZone.NoZone; }
private ZoneMembershipCondition BasicTest (SecurityZone zone) { ZoneMembershipCondition zmc = new ZoneMembershipCondition (zone); Assert.AreEqual (zone, zmc.SecurityZone, "SecurityZone"); Assert.IsFalse (zmc.Check (null), "Check(null)"); Assert.IsFalse (zmc.Check (allEmpty), "Check(empty)"); Assert.IsFalse (zmc.Check (hostOther), "Check(hostOther)"); Assert.IsFalse (zmc.Check (assemblyOther), "Check(assemblyOther)"); ZoneMembershipCondition copy = (ZoneMembershipCondition) zmc.Copy (); Assert.IsTrue (zmc.Equals (copy), "Equals-1"); Assert.IsTrue (copy.Equals (zmc), "Equals-2"); Assert.IsFalse (Object.ReferenceEquals (zmc, copy), "!ReferenceEquals"); Assert.IsFalse (zmc.Equals (null), "Equals-3"); Assert.IsFalse (zmc.Equals (wrongEvidence), "Equals-4"); SecurityElement se = zmc.ToXml (); copy.FromXml (se); Assert.IsTrue (zmc.Equals (copy), "Equals-5"); Assert.AreEqual (se.ToString (), zmc.ToXml (null).ToString (), "Equals-6"); Assert.IsTrue (zmc.ToString ().StartsWith ("Zone - "), "ToString-1"); Assert.IsTrue (zmc.ToString ().EndsWith (zmc.SecurityZone.ToString ()), "ToString-2"); Assert.AreEqual (zmc.SecurityZone.GetHashCode (), zmc.GetHashCode (), "GetHashCode"); return zmc; // for further tests }
private static extern void GetLocationEvidence(SafePEFileHandle peFile, out SecurityZone zone, StringHandleOnStack retUrl);
public ZoneIdentityPermission(SecurityZone zone) { }
[System.Security.SecuritySafeCritical] // auto-generated public SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); Action = SecurityAction.Demand; if(permThatFailed != null) m_typeOfPermissionThatFailed = permThatFailed.GetType(); FirstPermissionThatFailed = permThatFailed; Demanded = demanded; m_granted = ""; m_refused = ""; DenySetInstance = deny; PermitOnlySetInstance = permitOnly; m_assemblyName = null; Method = method; m_zone = SecurityZone.NoZone; m_url = ""; m_debugString = this.ToString(true, false); }
[System.Security.SecuritySafeCritical] // auto-generated public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); Action = action; if(permThatFailed != null) m_typeOfPermissionThatFailed = permThatFailed.GetType(); FirstPermissionThatFailed = permThatFailed; Demanded = demanded; m_granted = (grant == null ? "" : grant.ToXml().ToString()); m_refused = (refused == null ? "" : refused.ToXml().ToString()); m_denied = ""; m_permitOnly = ""; m_assemblyName = assemblyName; Method = method; m_url = ""; m_zone = SecurityZone.NoZone; if(evidence != null) { Url url = evidence.GetHostEvidence<Url>(); if(url != null) m_url = url.GetURLString().ToString(); Zone zone = evidence.GetHostEvidence<Zone>(); if(zone != null) m_zone = zone.SecurityZone; } m_debugString = this.ToString(true, false); }
[System.Security.SecuritySafeCritical] // auto-generated protected SecurityException(SerializationInfo info, StreamingContext context) : base (info, context) { if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); try { m_action = (SecurityAction)info.GetValue(ActionName, typeof(SecurityAction)); m_permissionThatFailed = (String)info.GetValueNoThrow(FirstPermissionThatFailedName, typeof(String)); m_demanded = (String)info.GetValueNoThrow(DemandedName, typeof(String)); m_granted = (String)info.GetValueNoThrow(GrantedSetName, typeof(String)); m_refused = (String)info.GetValueNoThrow(RefusedSetName, typeof(String)); m_denied = (String)info.GetValueNoThrow(DeniedName, typeof(String)); m_permitOnly = (String)info.GetValueNoThrow(PermitOnlyName, typeof(String)); m_assemblyName = (AssemblyName)info.GetValueNoThrow(Assembly_Name, typeof(AssemblyName)); m_serializedMethodInfo = (byte[])info.GetValueNoThrow(MethodName_Serialized, typeof(byte[])); m_strMethodInfo = (String)info.GetValueNoThrow(MethodName_String, typeof(String)); m_zone = (SecurityZone)info.GetValue(ZoneName, typeof(SecurityZone)); m_url = (String)info.GetValueNoThrow(UrlName, typeof(String)); } catch { m_action = 0; m_permissionThatFailed = ""; m_demanded = ""; m_granted = ""; m_refused = ""; m_denied = ""; m_permitOnly = ""; m_assemblyName = null; m_serializedMethodInfo = null; m_strMethodInfo = null; m_zone = SecurityZone.NoZone; m_url = ""; } }
public ZoneIdentityPermission( SecurityZone zone ) { this.SecurityZone = zone; }
//------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ private static void VerifyZone( SecurityZone zone ) { if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted) { throw new ArgumentException( Environment.GetResourceString("Argument_IllegalZone") ); } Contract.EndContractBlock(); }
public override void FromXml(SecurityElement esd) { m_zones = 0; CodeAccessPermission.ValidateElement( esd, this ); String eZone = esd.Attribute( "Zone" ); if (eZone != null) SecurityZone = (SecurityZone)Enum.Parse( typeof( SecurityZone ), eZone ); if(esd.Children != null) { foreach(SecurityElement child in esd.Children) { eZone = child.Attribute( "Zone" ); int enm = (int)Enum.Parse( typeof( SecurityZone ), eZone ); if(enm == (int)SecurityZone.NoZone) continue; m_zones |= ((uint)1 << enm); } } }
private void Resolve_Zone_Unrestricted_Attribute (SecurityZone zone, PolicyStatementAttribute attr) { IMembershipCondition mc = new ZoneMembershipCondition (zone); PolicyStatement ps = new PolicyStatement (new PermissionSet (PermissionState.Unrestricted)); ps.Attributes = attr; PolicyLevel pl = PolicyLevel.CreateAppDomainLevel (); pl.RootCodeGroup = new UnionCodeGroup (mc, ps); Resolve_Zone (pl, SecurityZone.Internet, attr, (zone == SecurityZone.Internet), 0); Resolve_Zone (pl, SecurityZone.Intranet, attr, (zone == SecurityZone.Intranet), 0); Resolve_Zone (pl, SecurityZone.MyComputer, attr, (zone == SecurityZone.MyComputer), 0); Resolve_Zone (pl, SecurityZone.NoZone, attr, (zone == SecurityZone.NoZone), 0); Resolve_Zone (pl, SecurityZone.Trusted, attr, (zone == SecurityZone.Trusted), 0); Resolve_Zone (pl, SecurityZone.Untrusted, attr, (zone == SecurityZone.Untrusted), 0); }
/// <internalonly/> int IBuiltInEvidence.InitFromBuffer( char[] buffer, int position ) { m_url = null; m_zone = (SecurityZone)BuiltInEvidenceHelper.GetIntFromCharArray(buffer, position); return position + 2; }
private void OnSerialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = null; m_zone = SecurityZone.NoZone; } }
internal Zone() { m_url = null; m_zone = SecurityZone.NoZone; }