Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,98 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// AllMembershipCondition.cs
//
// <OWNER>[....]</OWNER>
//
// Simple IMembershipCondition implementation that always passes
//
namespace System.Security.Policy {
using System;
using System.Security;
using System.Security.Util;
using System.Security.Permissions;
using System.Collections;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class AllMembershipCondition : IMembershipCondition, IConstantMembershipCondition, IReportMatchMembershipCondition
{
public AllMembershipCondition()
{
}
public bool Check( Evidence evidence )
{
object usedEvidence = null;
return (this as IReportMatchMembershipCondition).Check(evidence, out usedEvidence);
}
bool IReportMatchMembershipCondition.Check(Evidence evidence, out object usedEvidence)
{
usedEvidence = null;
return true;
}
public IMembershipCondition Copy()
{
return new AllMembershipCondition();
}
public override String ToString()
{
return Environment.GetResourceString( "All_ToString" );
}
public SecurityElement ToXml()
{
return ToXml( null );
}
public void FromXml( SecurityElement e )
{
FromXml( e, null );
}
public SecurityElement ToXml( PolicyLevel level )
{
SecurityElement root = new SecurityElement( "IMembershipCondition" );
System.Security.Util.XMLUtil.AddClassAttribute( root, this.GetType(), "System.Security.Policy.AllMembershipCondition" );
// If you hit this assert then most likely you are trying to change the name of this class.
// This is ok as long as you change the hard coded string above and change the assert below.
Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.AllMembershipCondition" ), "Class name changed!" );
root.AddAttribute( "version", "1" );
return root;
}
public void FromXml( SecurityElement e, PolicyLevel level )
{
if (e == null)
throw new ArgumentNullException("e");
if (!e.Tag.Equals( "IMembershipCondition" ))
{
throw new ArgumentException( Environment.GetResourceString( "Argument_MembershipConditionElement" ) );
}
Contract.EndContractBlock();
}
public override bool Equals( Object o )
{
return (o is AllMembershipCondition);
}
public override int GetHashCode()
{
return typeof( AllMembershipCondition ).GetHashCode();
}
}
}

View File

@@ -0,0 +1,96 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.Security.Policy
{
/// <summary>
/// Factory class which creates evidence on demand for an AppDomain
/// </summary>
internal sealed class AppDomainEvidenceFactory : IRuntimeEvidenceFactory
{
private AppDomain m_targetDomain;
private Evidence m_entryPointEvidence;
internal AppDomainEvidenceFactory(AppDomain target)
{
Contract.Assert(target != null);
Contract.Assert(target == AppDomain.CurrentDomain, "AppDomainEvidenceFactory should not be used across domains.");
m_targetDomain = target;
}
/// <summary>
/// AppDomain this factory generates evidence for
/// </summary>
public IEvidenceFactory Target
{
get { return m_targetDomain; }
}
/// <summary>
/// Return any evidence supplied by the AppDomain itself
/// </summary>
public IEnumerable<EvidenceBase> GetFactorySuppliedEvidence()
{
// AppDomains do not contain serialized evidence
return new EvidenceBase[] { };
}
/// <summary>
/// Generate evidence on demand for an AppDomain
/// </summary>
[SecuritySafeCritical]
public EvidenceBase GenerateEvidence(Type evidenceType)
{
// For v1.x compatibility, the default AppDomain has the same evidence as the entry point
// assembly. Since other AppDomains inherit their evidence from the default AppDomain by
// default, they also use the entry point assembly.
BCLDebug.Assert(m_targetDomain == AppDomain.CurrentDomain, "AppDomainEvidenceFactory should not be used across domains.");
if (m_targetDomain.IsDefaultAppDomain())
{
// If we don't already know the evidence for the entry point assembly, get that now. If we
// have a RuntimeAssembly go directly to its EvidenceNoDemand property to avoid the full
// demand that it will do on access to its Evidence property.
if (m_entryPointEvidence == null)
{
Assembly entryAssembly = Assembly.GetEntryAssembly();
RuntimeAssembly entryRuntimeAssembly = entryAssembly as RuntimeAssembly;
if (entryRuntimeAssembly != null)
{
m_entryPointEvidence = entryRuntimeAssembly.EvidenceNoDemand.Clone();
}
else if (entryAssembly != null)
{
m_entryPointEvidence = entryAssembly.Evidence;
}
}
// If the entry point assembly provided evidence, then we use that for the AppDomain
if (m_entryPointEvidence != null)
{
return m_entryPointEvidence.GetHostEvidence(evidenceType);
}
}
else
{
// If we're not the default domain, then we should inherit our evidence from the default
// domain -- so ask it what evidence it has of this type.
AppDomain defaultDomain = AppDomain.GetDefaultDomain();
return defaultDomain.GetHostEvidence(evidenceType);
}
// AppDomains do not generate any evidence on demand
return null;
}
}
}

View File

@@ -0,0 +1,97 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// ApplicationDirectory.cs
//
// <OWNER>[....]</OWNER>
//
// ApplicationDirectory is an evidence type representing the directory the assembly
// was loaded from.
//
namespace System.Security.Policy {
using System;
using System.IO;
using System.Security.Util;
using System.Collections;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ApplicationDirectory : EvidenceBase
{
private URLString m_appDirectory;
public ApplicationDirectory( String name )
{
if (name == null)
throw new ArgumentNullException( "name" );
Contract.EndContractBlock();
m_appDirectory = new URLString( name );
}
private ApplicationDirectory(URLString appDirectory)
{
Contract.Assert(appDirectory != null);
m_appDirectory = appDirectory;
}
public String Directory
{
get
{
return m_appDirectory.ToString();
}
}
public override bool Equals(Object o)
{
ApplicationDirectory other = o as ApplicationDirectory;
if (other == null)
{
return false;
}
return m_appDirectory.Equals(other.m_appDirectory);
}
public override int GetHashCode()
{
return this.m_appDirectory.GetHashCode();
}
public override EvidenceBase Clone()
{
return new ApplicationDirectory(m_appDirectory);
}
public Object Copy()
{
return Clone();
}
internal SecurityElement ToXml()
{
SecurityElement root = new SecurityElement( "System.Security.Policy.ApplicationDirectory" );
// If you hit this assert then most likely you are trying to change the name of this class.
// This is ok as long as you change the hard coded string above and change the assert below.
Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.ApplicationDirectory" ), "Class name changed!" );
root.AddAttribute( "version", "1" );
if (m_appDirectory != null)
root.AddChild( new SecurityElement( "Directory", m_appDirectory.ToString() ) );
return root;
}
public override String ToString()
{
return ToXml().ToString();
}
}
}

View File

@@ -0,0 +1,140 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// ApplicationDirectoryMembershipCondition.cs
//
// <OWNER>[....]</OWNER>
//
// Implementation of membership condition for "application directories"
//
namespace System.Security.Policy {
using System;
using SecurityElement = System.Security.SecurityElement;
using System.Security.Policy;
using URLString = System.Security.Util.URLString;
using System.Collections;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class ApplicationDirectoryMembershipCondition : IMembershipCondition, IConstantMembershipCondition, IReportMatchMembershipCondition
{
//------------------------------------------------------
//
// PRIVATE STATE DATA
//
//------------------------------------------------------
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
//
//------------------------------------------------------
public ApplicationDirectoryMembershipCondition()
{
}
//------------------------------------------------------
//
// IMEMBERSHIPCONDITION IMPLEMENTATION
//
//------------------------------------------------------
public bool Check( Evidence evidence )
{
object usedEvidence = null;
return (this as IReportMatchMembershipCondition).Check(evidence, out usedEvidence);
}
bool IReportMatchMembershipCondition.Check(Evidence evidence, out object usedEvidence)
{
usedEvidence = null;
if (evidence == null)
return false;
ApplicationDirectory dir = evidence.GetHostEvidence<ApplicationDirectory>();
Url url = evidence.GetHostEvidence<Url>();
if (dir != null && url != null)
{
// We need to add a wildcard at the end because IsSubsetOf keys off of it.
String appDir = dir.Directory;
if (appDir != null && appDir.Length > 1)
{
if (appDir[appDir.Length-1] == '/')
appDir += "*";
else
appDir += "/*";
URLString appDirString = new URLString(appDir);
if (url.GetURLString().IsSubsetOf(appDirString))
{
usedEvidence = dir;
return true;
}
}
}
return false;
}
public IMembershipCondition Copy()
{
return new ApplicationDirectoryMembershipCondition();
}
public SecurityElement ToXml()
{
return ToXml( null );
}
public void FromXml( SecurityElement e )
{
FromXml( e, null );
}
public SecurityElement ToXml( PolicyLevel level )
{
SecurityElement root = new SecurityElement( "IMembershipCondition" );
System.Security.Util.XMLUtil.AddClassAttribute( root, this.GetType(), "System.Security.Policy.ApplicationDirectoryMembershipCondition" );
// If you hit this assert then most likely you are trying to change the name of this class.
// This is ok as long as you change the hard coded string above and change the assert below.
BCLDebug.Assert( this.GetType().FullName.Equals( "System.Security.Policy.ApplicationDirectoryMembershipCondition" ), "Class name changed!" );
root.AddAttribute( "version", "1" );
return root;
}
public void FromXml( SecurityElement e, PolicyLevel level )
{
if (e == null)
throw new ArgumentNullException("e");
if (!e.Tag.Equals( "IMembershipCondition" ))
{
throw new ArgumentException( Environment.GetResourceString( "Argument_MembershipConditionElement" ) );
}
}
public override bool Equals( Object o )
{
return (o is ApplicationDirectoryMembershipCondition);
}
public override int GetHashCode()
{
return typeof( ApplicationDirectoryMembershipCondition ).GetHashCode();
}
public override String ToString()
{
return Environment.GetResourceString( "ApplicationDirectory_ToString" );
}
}
}

View File

@@ -0,0 +1,209 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// ApplicationSecurityInfo.cs
//
// The application security info holds all the security related information pertinent
// to the application. In some sense, it is the CLR public representation of the security
// information held in the manifest.
//
namespace System.Security.Policy {
using System.Collections;
using System.Deployment.Internal.Isolation;
using System.Deployment.Internal.Isolation.Manifest;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Util;
using System.Threading;
using System.Runtime.Versioning;
using System.Runtime.Hosting;
using System.Diagnostics.Contracts;
[System.Security.SecurityCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ApplicationSecurityInfo {
private ActivationContext m_context;
private object m_appId;
private object m_deployId;
private object m_defaultRequest;
private object m_appEvidence;
internal ApplicationSecurityInfo () {}
//
// Public.
//
public ApplicationSecurityInfo (ActivationContext activationContext) {
if (activationContext == null)
throw new ArgumentNullException("activationContext");
Contract.EndContractBlock();
m_context = activationContext;
}
public ApplicationId ApplicationId {
get {
if (m_appId == null && m_context != null) {
ICMS appManifest = m_context.ApplicationComponentManifest;
ApplicationId appId = ParseApplicationId(appManifest);
Interlocked.CompareExchange(ref m_appId, appId, null);
}
return m_appId as ApplicationId;
}
set {
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
m_appId = value;
}
}
public ApplicationId DeploymentId {
get {
if (m_deployId == null && m_context != null) {
ICMS deplManifest = m_context.DeploymentComponentManifest;
ApplicationId deplId = ParseApplicationId(deplManifest);
Interlocked.CompareExchange(ref m_deployId, deplId, null);
}
return m_deployId as ApplicationId;
}
set {
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
m_deployId = value;
}
}
public PermissionSet DefaultRequestSet {
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
get {
if (m_defaultRequest == null) {
PermissionSet defaultRequest = new PermissionSet(PermissionState.None);
if (m_context != null) {
// read the default request from the app manifest.
ICMS appManifest = m_context.ApplicationComponentManifest;
string defaultPSetId = ((IMetadataSectionEntry) appManifest.MetadataSectionEntry).defaultPermissionSetID;
object permissionSetObj = null;
if (defaultPSetId != null && defaultPSetId.Length > 0) {
((ISectionWithStringKey) appManifest.PermissionSetSection).Lookup(defaultPSetId, out permissionSetObj);
IPermissionSetEntry defaultPSet = permissionSetObj as IPermissionSetEntry;
if (defaultPSet != null) {
SecurityElement seDefaultPS = SecurityElement.FromString(defaultPSet.AllData.XmlSegment);
string unrestricted = seDefaultPS.Attribute("temp:Unrestricted");
if (unrestricted != null)
seDefaultPS.AddAttribute("Unrestricted", unrestricted);
// Look for "SameSite" request.
string sameSite = seDefaultPS.Attribute("SameSite");
if (String.Compare(sameSite, "Site", StringComparison.OrdinalIgnoreCase) == 0) {
Url url = new Url(m_context.Identity.CodeBase);
URLString urlString = url.GetURLString();
// Create a same site web permission for HTTP deployed applications. We'll
// always use a v2.0 WebPermission for this because this XML is loadable
// on all versions of the framework that support ClickOnce. This allows
// newer versions of the framework to create ApplicationSecurityInfo objects
// that may eventually be used by applications running against older versions
// of the framework.
NetCodeGroup netCodeGroup = new NetCodeGroup(new AllMembershipCondition());
SecurityElement webPermission =
netCodeGroup.CreateWebPermission(urlString.Host,
urlString.Scheme,
urlString.Port,
"System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken);
if (webPermission != null) {
seDefaultPS.AddChild(webPermission);
}
if (String.Compare("file:", 0, m_context.Identity.CodeBase, 0, 5, StringComparison.OrdinalIgnoreCase) == 0) {
FileCodeGroup fileCodeGroup = new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery);
PolicyStatement ps = fileCodeGroup.CalculatePolicy(url);
if (ps != null) {
PermissionSet filePermissionSet = ps.PermissionSet;
if (filePermissionSet != null) {
seDefaultPS.AddChild(filePermissionSet.GetPermission(typeof(FileIOPermission)).ToXml());
}
}
}
}
// We need to use a ReadOnlyPermissionSet to ensure that any permissions in
// the manifest which were created on a previous runtime are stored back to
// the application store in a format that the previous runtime can understand.
defaultRequest = new ReadOnlyPermissionSet(seDefaultPS);
}
}
}
Interlocked.CompareExchange(ref m_defaultRequest, defaultRequest, null);
}
return m_defaultRequest as PermissionSet;
}
set {
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
m_defaultRequest = value;
}
}
public Evidence ApplicationEvidence {
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
get {
if (m_appEvidence == null) {
Evidence appEvidence = new Evidence();
if (m_context != null) {
appEvidence = new Evidence();
Url deploymentUrl = new Url(m_context.Identity.CodeBase);
appEvidence.AddHostEvidence(deploymentUrl);
appEvidence.AddHostEvidence(Zone.CreateFromUrl(m_context.Identity.CodeBase));
if (String.Compare("file:", 0, m_context.Identity.CodeBase, 0, 5, StringComparison.OrdinalIgnoreCase) != 0) {
appEvidence.AddHostEvidence(Site.CreateFromUrl(m_context.Identity.CodeBase));
}
appEvidence.AddHostEvidence(new StrongName(new StrongNamePublicKeyBlob(DeploymentId.m_publicKeyToken),
DeploymentId.Name,
DeploymentId.Version));
appEvidence.AddHostEvidence(new ActivationArguments(m_context));
}
Interlocked.CompareExchange(ref m_appEvidence, appEvidence, null);
}
return m_appEvidence as Evidence;
}
set {
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
m_appEvidence = value;
}
}
//
// Internal.
//
private static ApplicationId ParseApplicationId (ICMS manifest) {
if (manifest.Identity == null)
return null;
return new ApplicationId(Hex.DecodeHexString(manifest.Identity.GetAttribute("", "publicKeyToken")),
manifest.Identity.GetAttribute("", "name"),
new Version(manifest.Identity.GetAttribute("", "version")),
manifest.Identity.GetAttribute("", "processorArchitecture"),
manifest.Identity.GetAttribute("", "culture"));
}
}
}

View File

@@ -0,0 +1,182 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// ApplicationSecurityManager.cs
//
namespace System.Security.Policy {
using System.Deployment.Internal.Isolation;
using System.Deployment.Internal.Isolation.Manifest;
using System.IO;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Security.Util;
using System.Diagnostics.Contracts;
using System.Reflection;
[System.Runtime.InteropServices.ComVisible(true)]
public static class ApplicationSecurityManager {
private static volatile IApplicationTrustManager m_appTrustManager = null;
//
// Public static methods.
//
[System.Security.SecuritySafeCritical] // auto-generated
static ApplicationSecurityManager()
{
}
[System.Security.SecurityCritical] // auto-generated_required
[SecurityPermissionAttribute(SecurityAction.Assert, Unrestricted=true)]
public static bool DetermineApplicationTrust (ActivationContext activationContext, TrustManagerContext context) {
if (activationContext == null)
throw new ArgumentNullException("activationContext");
Contract.EndContractBlock();
ApplicationTrust appTrust = null;
AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
if (domainManager != null) {
HostSecurityManager securityManager = domainManager.HostSecurityManager;
if ((securityManager != null) && ((securityManager.Flags & HostSecurityManagerOptions.HostDetermineApplicationTrust) == HostSecurityManagerOptions.HostDetermineApplicationTrust)) {
appTrust = securityManager.DetermineApplicationTrust(CmsUtils.MergeApplicationEvidence(null, activationContext.Identity, activationContext, null), null, context);
if (appTrust == null)
return false;
return appTrust.IsApplicationTrustedToRun;
}
}
appTrust = DetermineApplicationTrustInternal(activationContext, context);
if (appTrust == null)
return false;
return appTrust.IsApplicationTrustedToRun;
}
//
// Public static properties.
//
public static ApplicationTrustCollection UserApplicationTrusts {
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPolicy)]
get {
return new ApplicationTrustCollection(true);
}
}
public static IApplicationTrustManager ApplicationTrustManager {
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPolicy)]
get {
if (m_appTrustManager == null) {
m_appTrustManager = DecodeAppTrustManager();
if (m_appTrustManager == null)
throw new PolicyException(Environment.GetResourceString("Policy_NoTrustManager"));
}
return m_appTrustManager;
}
}
//
// Internal
//
[System.Security.SecurityCritical] // auto-generated
internal static ApplicationTrust DetermineApplicationTrustInternal (ActivationContext activationContext, TrustManagerContext context) {
ApplicationTrust trust = null;
ApplicationTrustCollection userTrusts = new ApplicationTrustCollection(true);
// See if there is a persisted trust decision for this application.
if ((context == null || !context.IgnorePersistedDecision)) {
trust = userTrusts[activationContext.Identity.FullName];
if (trust != null)
return trust;
}
// There is no cached trust decision so invoke the trust manager.
trust = ApplicationTrustManager.DetermineApplicationTrust(activationContext, context);
if (trust == null)
trust = new ApplicationTrust(activationContext.Identity);
// make sure the application identity is correctly set.
trust.ApplicationIdentity = activationContext.Identity;
if (trust.Persist)
userTrusts.Add(trust);
return trust;
}
//
// Private.
//
private static string s_machineConfigFile = Config.MachineDirectory + "applicationtrust.config";
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static IApplicationTrustManager DecodeAppTrustManager () {
if (!File.InternalExists(s_machineConfigFile))
goto defaultTrustManager;
// A config file exists. Decode the trust manager from its Xml.
String configFileStr;
using (FileStream contents = new FileStream(s_machineConfigFile, FileMode.Open, FileAccess.Read))
{
configFileStr = new StreamReader(contents).ReadToEnd();
}
SecurityElement elRoot = SecurityElement.FromString(configFileStr);
SecurityElement elMscorlib = elRoot.SearchForChildByTag("mscorlib");
if (elMscorlib == null)
goto defaultTrustManager;
SecurityElement elSecurity = elMscorlib.SearchForChildByTag("security");
if (elSecurity == null)
goto defaultTrustManager;
SecurityElement elPolicy = elSecurity.SearchForChildByTag("policy");
if (elPolicy == null)
goto defaultTrustManager;
SecurityElement elSecurityManager = elPolicy.SearchForChildByTag("ApplicationSecurityManager");
if (elSecurityManager == null)
goto defaultTrustManager;
SecurityElement elTrustManager = elSecurityManager.SearchForChildByTag("IApplicationTrustManager");
if (elTrustManager == null)
goto defaultTrustManager;
IApplicationTrustManager appTrustManager = DecodeAppTrustManagerFromElement(elTrustManager);
if (appTrustManager == null)
goto defaultTrustManager;
return appTrustManager;
defaultTrustManager:
return DecodeAppTrustManagerFromElement(CreateDefaultApplicationTrustManagerElement());
}
[System.Security.SecurityCritical] // auto-generated
private static SecurityElement CreateDefaultApplicationTrustManagerElement() {
SecurityElement elTrustManager = new SecurityElement("IApplicationTrustManager");
elTrustManager.AddAttribute("class",
"System.Security.Policy.TrustManager, System.Windows.Forms, Version=" + ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetVersion() + ", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken);
elTrustManager.AddAttribute("version", "1");
return elTrustManager;
}
[System.Security.SecurityCritical] // auto-generated
private static IApplicationTrustManager DecodeAppTrustManagerFromElement (SecurityElement elTrustManager) {
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
string trustManagerName = elTrustManager.Attribute("class");
Type tmClass = Type.GetType(trustManagerName, false, false);
if (tmClass == null)
return null;
IApplicationTrustManager appTrustManager = Activator.CreateInstance(tmClass) as IApplicationTrustManager;
if (appTrustManager != null)
appTrustManager.FromXml(elTrustManager);
return appTrustManager;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,243 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Policy
{
/// <summary>
/// Factory class which can create evidence on demand for an assembly
/// </summary>
internal sealed class AssemblyEvidenceFactory : IRuntimeEvidenceFactory
{
private PEFileEvidenceFactory m_peFileFactory;
private RuntimeAssembly m_targetAssembly;
/// <summary>
/// Create a factory which can generate evidence for the specified assembly
/// </summary>
private AssemblyEvidenceFactory(RuntimeAssembly targetAssembly, PEFileEvidenceFactory peFileFactory)
{
Contract.Assert(targetAssembly != null);
Contract.Assert(peFileFactory != null);
m_targetAssembly = targetAssembly;
m_peFileFactory = peFileFactory;
}
/// <summary>
/// PEFile that the assembly is loaded from
/// </summary>
internal SafePEFileHandle PEFile
{
[SecurityCritical]
get { return m_peFileFactory.PEFile; }
}
/// <summary>
/// Assembly that the evidence generated is for
/// </summary>
public IEvidenceFactory Target
{
get { return m_targetAssembly; }
}
/// <summary>
/// Generate a specific type of evidence for this assembly
/// </summary>
public EvidenceBase GenerateEvidence(Type evidenceType)
{
// Assembly evidence is a superset of the evidence that a PEFile can supply, so first see if the
// requested evidence type can be generated by the assembly's PEFile
EvidenceBase evidence = m_peFileFactory.GenerateEvidence(evidenceType);
if (evidence != null)
{
return evidence;
}
// If the PEFile didn't know about this type of evidence, see if it is an evidence type that the
// Assembly knows how to generate
if (evidenceType == typeof(GacInstalled))
{
return GenerateGacEvidence();
}
else if (evidenceType == typeof(Hash))
{
return GenerateHashEvidence();
}
#pragma warning disable 618 // We need to generate PermissionRequestEvidence in compatibility mode
else if (evidenceType == typeof(PermissionRequestEvidence))
{
return GeneratePermissionRequestEvidence();
}
#pragma warning restore 618
else if (evidenceType == typeof(StrongName))
{
return GenerateStrongNameEvidence();
}
return null;
}
/// <summary>
/// Generate evidence if the assembly is installed in the GAC
/// </summary>
private GacInstalled GenerateGacEvidence()
{
if (!m_targetAssembly.GlobalAssemblyCache)
{
return null;
}
m_peFileFactory.FireEvidenceGeneratedEvent(EvidenceTypeGenerated.Gac);
return new GacInstalled();
}
/// <summary>
/// Generate evidence for the assembly's hash value
/// </summary>
private Hash GenerateHashEvidence()
{
if (m_targetAssembly.IsDynamic)
{
return null;
}
m_peFileFactory.FireEvidenceGeneratedEvent(EvidenceTypeGenerated.Hash);
return new Hash(m_targetAssembly);
}
#pragma warning disable 618 // We need to generate PermissionRequestEvidence in compatibility mode
/// <summary>
/// Generate evidence for the assembly's declarative security
/// </summary>
[SecuritySafeCritical]
private PermissionRequestEvidence GeneratePermissionRequestEvidence()
{
Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled);
PermissionSet minimumPermissions = null;
PermissionSet optionalPermissions = null;
PermissionSet refusedPermissions = null;
GetAssemblyPermissionRequests(m_targetAssembly.GetNativeHandle(),
JitHelpers.GetObjectHandleOnStack(ref minimumPermissions),
JitHelpers.GetObjectHandleOnStack(ref optionalPermissions),
JitHelpers.GetObjectHandleOnStack(ref refusedPermissions));
if (minimumPermissions != null || optionalPermissions != null || refusedPermissions != null)
{
return new PermissionRequestEvidence(minimumPermissions,
optionalPermissions,
refusedPermissions);
}
return null;
}
#pragma warning restore 618
/// <summary>
/// Generate evidence for this file's strong name
/// </summary>
[SecuritySafeCritical]
private StrongName GenerateStrongNameEvidence()
{
byte[] publicKeyBlob = null;
string simpleName = null;
ushort majorVersion = 0;
ushort minorVersion = 0;
ushort build = 0;
ushort revision = 0;
GetStrongNameInformation(m_targetAssembly.GetNativeHandle(),
JitHelpers.GetObjectHandleOnStack(ref publicKeyBlob),
JitHelpers.GetStringHandleOnStack(ref simpleName),
out majorVersion,
out minorVersion,
out build,
out revision);
if (publicKeyBlob == null || publicKeyBlob.Length == 0)
{
return null;
}
return new StrongName(new StrongNamePublicKeyBlob(publicKeyBlob),
simpleName,
new Version(majorVersion, minorVersion, build, revision),
m_targetAssembly);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
private static extern void GetAssemblyPermissionRequests(RuntimeAssembly assembly,
ObjectHandleOnStack retMinimumPermissions,
ObjectHandleOnStack retOptionalPermissions,
ObjectHandleOnStack retRefusedPermissions);
/// <summary>
/// Get any evidence that was serialized into the assembly
/// </summary>
public IEnumerable<EvidenceBase> GetFactorySuppliedEvidence()
{
// The PEFile knows how to read the serialized evidence, so we can just delegate to it
return m_peFileFactory.GetFactorySuppliedEvidence();
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SecurityCritical]
[SuppressUnmanagedCodeSecurity]
private static extern void GetStrongNameInformation(RuntimeAssembly assembly,
ObjectHandleOnStack retPublicKeyBlob,
StringHandleOnStack retSimpleName,
[Out] out ushort majorVersion,
[Out] out ushort minorVersion,
[Out] out ushort build,
[Out] out ushort revision);
/// <summary>
/// Retarget an evidence object from generating evidence for a PEFile to generating evidence for
/// the file's assembly.
/// </summary>
[SecurityCritical]
private static Evidence UpgradeSecurityIdentity(Evidence peFileEvidence, RuntimeAssembly targetAssembly)
{
Contract.Assert(peFileEvidence != null);
Contract.Assert(targetAssembly != null);
Contract.Assert(peFileEvidence.Target is PEFileEvidenceFactory, "Expected upgrade path is from PEFile to Assembly");
peFileEvidence.Target = new AssemblyEvidenceFactory(targetAssembly,
peFileEvidence.Target as PEFileEvidenceFactory);
// Whidbey hosts would provide evidence for assemblies up front rather than on demand. If there
// is a HostSecurityManager which does want to provide evidence, then we should provide it the
// opprotunity to do the same for compatibility.
HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager;
if ((securityManager.Flags & HostSecurityManagerOptions.HostAssemblyEvidence) == HostSecurityManagerOptions.HostAssemblyEvidence)
{
peFileEvidence = securityManager.ProvideAssemblyEvidence(targetAssembly, peFileEvidence);
if (peFileEvidence == null)
{
throw new InvalidOperationException(Environment.GetResourceString("Policy_NullHostEvidence", securityManager.GetType().FullName, targetAssembly.FullName));
}
}
return peFileEvidence;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,195 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization.Formatters.Binary;
#endif // FEATURE_SERIALIZATION
using System.Security.Permissions;
namespace System.Security.Policy
{
/// <summary>
/// Base class from which all objects to be used as Evidence must derive
/// </summary>
[ComVisible(true)]
[Serializable]
#pragma warning disable 618
[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
#pragma warning restore 618
public abstract class EvidenceBase
{
protected EvidenceBase()
{
#if FEATURE_SERIALIZATION
// All objects to be used as evidence must be serializable. Make sure that any derived types
// are marked serializable to enforce this, since the attribute does not inherit down to derived
// classes.
if (!GetType().IsSerializable)
{
throw new InvalidOperationException(Environment.GetResourceString("Policy_EvidenceMustBeSerializable"));
}
#endif // FEATURE_SERIALIZATION
}
/// <remarks>
/// Since legacy evidence objects would be cloned by being serialized, the default implementation
/// of EvidenceBase will do the same.
/// </remarks>
#pragma warning disable 618
[SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)]
[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
#pragma warning restore 618
[SecuritySafeCritical]
public virtual EvidenceBase Clone()
{
#if FEATURE_SERIALIZATION
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
return formatter.Deserialize(memoryStream) as EvidenceBase;
}
#else // !FEATURE_SERIALIZATION
throw new NotImplementedException();
#endif // FEATURE_SERIALIZATION
}
}
/// <summary>
/// Interface for types which wrap Whidbey evidence objects for compatibility with v4 evidence rules
/// </summary>
internal interface ILegacyEvidenceAdapter
{
object EvidenceObject { get; }
Type EvidenceType { get; }
}
/// <summary>
/// Wrapper class to hold legacy evidence objects which do not derive from EvidenceBase, and allow
/// them to be held in the Evidence collection which expects to maintain lists of EvidenceBase only
/// </summary>
[Serializable]
internal sealed class LegacyEvidenceWrapper : EvidenceBase, ILegacyEvidenceAdapter
{
private object m_legacyEvidence;
internal LegacyEvidenceWrapper(object legacyEvidence)
{
Contract.Assert(legacyEvidence != null);
Contract.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper");
Contract.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable");
m_legacyEvidence = legacyEvidence;
}
public object EvidenceObject
{
get { return m_legacyEvidence; }
}
public Type EvidenceType
{
get { return m_legacyEvidence.GetType(); }
}
public override bool Equals(object obj)
{
return m_legacyEvidence.Equals(obj);
}
public override int GetHashCode()
{
return m_legacyEvidence.GetHashCode();
}
#pragma warning disable 618
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
#pragma warning restore 618
[SecuritySafeCritical]
public override EvidenceBase Clone()
{
return base.Clone();
}
}
/// <summary>
/// Pre-v4 versions of the runtime allow multiple pieces of evidence that all have the same type.
/// This type wraps those evidence objects into a single type of list, allowing legacy code to continue
/// to work with the Evidence collection that does not expect multiple evidences of the same type.
///
/// This may not be limited to LegacyEvidenceWrappers, since it's valid for legacy code to add multiple
/// objects of built-in evidence to an Evidence collection. The built-in evidence now derives from
/// EvienceObject, so when the legacy code runs on v4, it may end up attempting to add multiple
/// Hash evidences for intsance.
/// </summary>
[Serializable]
internal sealed class LegacyEvidenceList : EvidenceBase, IEnumerable<EvidenceBase>, ILegacyEvidenceAdapter
{
private List<EvidenceBase> m_legacyEvidenceList = new List<EvidenceBase>();
public object EvidenceObject
{
get
{
// We'll choose the first item in the list to represent us if we're forced to return only
// one object. This can occur if multiple pieces of evidence are added via the legacy APIs,
// and then the new APIs are used to retrieve that evidence.
return m_legacyEvidenceList.Count > 0 ? m_legacyEvidenceList[0] : null;
}
}
public Type EvidenceType
{
get
{
Contract.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are");
ILegacyEvidenceAdapter adapter = m_legacyEvidenceList[0] as ILegacyEvidenceAdapter;
return adapter == null ? m_legacyEvidenceList[0].GetType() : adapter.EvidenceType;
}
}
public void Add(EvidenceBase evidence)
{
Contract.Assert(evidence != null);
Contract.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType),
"LegacyEvidenceList must be ----geonous");
Contract.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
"Attempt to add a legacy evidence list to another legacy evidence list");
m_legacyEvidenceList.Add(evidence);
}
public IEnumerator<EvidenceBase> GetEnumerator()
{
return m_legacyEvidenceList.GetEnumerator();
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return m_legacyEvidenceList.GetEnumerator();
}
#pragma warning disable 618
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
#pragma warning restore 618
[SecuritySafeCritical]
public override EvidenceBase Clone()
{
return base.Clone();
}
}
}

View File

@@ -0,0 +1,164 @@
// ==--==
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Security.Policy
{
/// <summary>
/// Descriptor stored in the Evidence collection to detail the information we have about a type of
/// evidence. This descriptor also stores any evidence that's been generated of the specific type.
/// </summary>
[Serializable]
internal sealed class EvidenceTypeDescriptor
{
[NonSerialized]
private bool m_hostCanGenerate;
[NonSerialized]
private bool m_generated;
private EvidenceBase m_hostEvidence;
private EvidenceBase m_assemblyEvidence;
// EvidenceTypeDescriptors are stored in Evidence indexed by the type they describe, so this
// information is redundant. We keep it around in checked builds to help debugging, but we can drop
// it from retial builds.
#if _DEBUG
[NonSerialized]
private Type m_evidenceType;
#endif // _DEBUG
public EvidenceTypeDescriptor()
{
}
/// <summary>
/// Make a deep copy of a type descriptor
/// </summary>
private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor)
{
Contract.Assert(descriptor != null);
m_hostCanGenerate = descriptor.m_hostCanGenerate;
if (descriptor.m_assemblyEvidence != null)
{
m_assemblyEvidence = descriptor.m_assemblyEvidence.Clone() as EvidenceBase;
}
if (descriptor.m_hostEvidence != null)
{
m_hostEvidence = descriptor.m_hostEvidence.Clone() as EvidenceBase;
}
#if _DEBUG
m_evidenceType = descriptor.m_evidenceType;
#endif // _DEBUG
}
/// <summary>
/// Evidence of this type supplied by the assembly
/// </summary>
public EvidenceBase AssemblyEvidence
{
get { return m_assemblyEvidence; }
set
{
Contract.Assert(value != null);
#if _DEBUG
Contract.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
#endif
m_assemblyEvidence = value;
}
}
/// <summary>
/// Flag indicating that we've already attempted to generate this type of evidence
/// </summary>
public bool Generated
{
get { return m_generated; }
set
{
Contract.Assert(value, "Attempt to clear the Generated flag");
m_generated = value;
}
}
/// <summary>
/// Has the HostSecurityManager has told us that it can potentially generate evidence of this type
/// </summary>
public bool HostCanGenerate
{
get { return m_hostCanGenerate; }
set
{
Contract.Assert(value, "Attempt to clear HostCanGenerate flag");
m_hostCanGenerate = value;
}
}
/// <summary>
/// Evidence of this type supplied by the CLR or the host
/// </summary>
public EvidenceBase HostEvidence
{
get { return m_hostEvidence; }
set
{
Contract.Assert(value != null);
#if _DEBUG
Contract.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
#endif
m_hostEvidence = value;
}
}
#if _DEBUG
/// <summary>
/// Verify that evidence being stored in this descriptor is of the correct type
/// </summary>
private bool CheckEvidenceType(EvidenceBase evidence)
{
Contract.Assert(evidence != null);
ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter;
Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType;
return m_evidenceType == null || m_evidenceType.IsAssignableFrom(storedType);
}
#endif // _DEBUG
/// <summary>
/// Make a deep copy of this descriptor
/// </summary>
public EvidenceTypeDescriptor Clone()
{
return new EvidenceTypeDescriptor(this);
}
#if _DEBUG
/// <summary>
/// Set the type that this evidence descriptor refers to.
/// </summary>
internal void SetEvidenceType(Type evidenceType)
{
Contract.Assert(evidenceType != null);
Contract.Assert(m_evidenceType == null, "Attempt to reset evidence type");
m_evidenceType = evidenceType;
}
#endif // _DEBUG
}
}

View File

@@ -0,0 +1,207 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// FileCodeGroup.cs
//
// Representation for code groups used for the policy mechanism.
//
namespace System.Security.Policy {
using System;
using System.Collections;
using System.Globalization;
using System.Security.Permissions;
using System.Security.Util;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class FileCodeGroup : CodeGroup, IUnionSemanticCodeGroup {
private FileIOPermissionAccess m_access;
internal FileCodeGroup() : base() {}
public FileCodeGroup(IMembershipCondition membershipCondition, FileIOPermissionAccess access)
: base(membershipCondition, (PolicyStatement)null) {
m_access = access;
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public override PolicyStatement Resolve(Evidence evidence) {
if (evidence == null)
throw new ArgumentNullException("evidence");
Contract.EndContractBlock();
object usedEvidence = null;
if (PolicyManager.CheckMembershipCondition(MembershipCondition, evidence, out usedEvidence)) {
PolicyStatement thisPolicy = CalculateAssemblyPolicy(evidence);
// If any delay-evidence was used to generate this grant set, then we need to keep track of
// that for potentially later forcing it to be verified.
IDelayEvaluatedEvidence delayEvidence = usedEvidence as IDelayEvaluatedEvidence;
bool delayEvidenceNeedsVerification = delayEvidence != null && !delayEvidence.IsVerified;
if (delayEvidenceNeedsVerification) {
thisPolicy.AddDependentEvidence(delayEvidence);
}
bool foundExclusiveChild = false;
IEnumerator enumerator = this.Children.GetEnumerator();
while (enumerator.MoveNext() && !foundExclusiveChild) {
PolicyStatement childPolicy = PolicyManager.ResolveCodeGroup(enumerator.Current as CodeGroup,
evidence);
if (childPolicy != null) {
thisPolicy.InplaceUnion(childPolicy);
if ((childPolicy.Attributes & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive) {
foundExclusiveChild = true;
}
}
}
return thisPolicy;
}
else {
return null;
}
}
/// <internalonly/>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
PolicyStatement IUnionSemanticCodeGroup.InternalResolve(Evidence evidence) {
if (evidence == null)
throw new ArgumentNullException("evidence");
Contract.EndContractBlock();
if (this.MembershipCondition.Check(evidence)) {
return CalculateAssemblyPolicy(evidence);
}
return null;
}
public override CodeGroup ResolveMatchingCodeGroups(Evidence evidence) {
if (evidence == null)
throw new ArgumentNullException("evidence");
Contract.EndContractBlock();
if (this.MembershipCondition.Check(evidence)) {
CodeGroup retGroup = this.Copy();
retGroup.Children = new ArrayList();
IEnumerator enumerator = this.Children.GetEnumerator();
while (enumerator.MoveNext()) {
CodeGroup matchingGroups = ((CodeGroup)enumerator.Current).ResolveMatchingCodeGroups(evidence);
// If the child has a policy, we are done.
if (matchingGroups != null)
retGroup.AddChild(matchingGroups);
}
return retGroup;
}
else {
return null;
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal PolicyStatement CalculatePolicy(Url url) {
URLString urlString = url.GetURLString();
if (String.Compare(urlString.Scheme, "file", StringComparison.OrdinalIgnoreCase) != 0)
return null;
string directory = urlString.GetDirectoryName();
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.SetPermission(new FileIOPermission(m_access, System.IO.Path.GetFullPath(directory)));
return new PolicyStatement(permSet, PolicyStatementAttribute.Nothing);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private PolicyStatement CalculateAssemblyPolicy(Evidence evidence) {
PolicyStatement thisPolicy = null;
Url url = evidence.GetHostEvidence<Url>();
if (url != null) {
thisPolicy = CalculatePolicy(url);
}
if (thisPolicy == null) {
thisPolicy = new PolicyStatement(new PermissionSet(false), PolicyStatementAttribute.Nothing);
}
return thisPolicy;
}
public override CodeGroup Copy() {
FileCodeGroup group = new FileCodeGroup(this.MembershipCondition, this.m_access);
group.Name = this.Name;
group.Description = this.Description;
IEnumerator enumerator = this.Children.GetEnumerator();
while (enumerator.MoveNext()) {
group.AddChild((CodeGroup)enumerator.Current);
}
return group;
}
public override string MergeLogic {
get {
return Environment.GetResourceString("MergeLogic_Union");
}
}
public override string PermissionSetName {
get {
return Environment.GetResourceString("FileCodeGroup_PermissionSet", XMLUtil.BitFieldEnumToString(typeof(FileIOPermissionAccess), m_access));
}
}
public override string AttributeString {
get {
return null;
}
}
protected override void CreateXml(SecurityElement element, PolicyLevel level) {
element.AddAttribute("Access", XMLUtil.BitFieldEnumToString(typeof(FileIOPermissionAccess), m_access));
}
protected override void ParseXml(SecurityElement e, PolicyLevel level) {
string access = e.Attribute("Access");
if (access != null)
m_access = (FileIOPermissionAccess) Enum.Parse(typeof(FileIOPermissionAccess), access);
else
m_access = FileIOPermissionAccess.NoAccess;
}
public override bool Equals(Object o) {
FileCodeGroup that = (o as FileCodeGroup);
if (that != null && base.Equals(that)) {
if (this.m_access == that.m_access)
return true;
}
return false;
}
public override int GetHashCode() {
return base.GetHashCode() + m_access.GetHashCode();
}
internal override string GetTypeName() {
return "System.Security.Policy.FileCodeGroup";
}
}
}

View File

@@ -0,0 +1,187 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// FirstMatchCodeGroup.cs
//
// <OWNER>[....]</OWNER>
//
// Representation for code groups used for the policy mechanism
//
namespace System.Security.Policy {
using System;
using System.Security;
using System.Security.Util;
using System.Collections;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[Obsolete("This type is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
sealed public class FirstMatchCodeGroup : CodeGroup
{
internal FirstMatchCodeGroup()
: base()
{
}
public FirstMatchCodeGroup( IMembershipCondition membershipCondition, PolicyStatement policy )
: base( membershipCondition, policy )
{
}
[System.Security.SecuritySafeCritical] // auto-generated
public override PolicyStatement Resolve( Evidence evidence )
{
if (evidence == null)
throw new ArgumentNullException("evidence");
Contract.EndContractBlock();
object usedEvidence = null;
if (PolicyManager.CheckMembershipCondition(MembershipCondition,
evidence,
out usedEvidence))
{
PolicyStatement childPolicy = null;
IEnumerator enumerator = this.Children.GetEnumerator();
while (enumerator.MoveNext())
{
childPolicy = PolicyManager.ResolveCodeGroup(enumerator.Current as CodeGroup,
evidence);
// If the child has a policy, we are done.
if (childPolicy != null)
{
break;
}
}
// If any delay-evidence was used to generate this grant set, then we need to keep track of
// that for potentially later forcing it to be verified.
IDelayEvaluatedEvidence delayEvidence = usedEvidence as IDelayEvaluatedEvidence;
bool delayEvidenceNeedsVerification = delayEvidence != null && !delayEvidence.IsVerified;
PolicyStatement thisPolicy = this.PolicyStatement; // PolicyStatement getter makes a copy for us
if (thisPolicy == null)
{
// We didn't add any permissions, but we enabled our children to be evaluated, and
// therefore its grant set is dependent on any of our delay evidence.
if (delayEvidenceNeedsVerification)
{
childPolicy = childPolicy.Copy();
childPolicy.AddDependentEvidence(delayEvidence);
}
return childPolicy;
}
else if (childPolicy != null)
{
// Combine the child and this policy and return it.
PolicyStatement combined = thisPolicy.Copy();
if (delayEvidenceNeedsVerification)
{
combined.AddDependentEvidence(delayEvidence);
}
combined.InplaceUnion(childPolicy);
return combined;
}
else
{
// Otherwise we just copy the this policy.
if (delayEvidenceNeedsVerification)
{
thisPolicy.AddDependentEvidence(delayEvidence);
}
return thisPolicy;
}
}
else
{
return null;
}
}
public override CodeGroup ResolveMatchingCodeGroups( Evidence evidence )
{
if (evidence == null)
throw new ArgumentNullException("evidence");
Contract.EndContractBlock();
if (this.MembershipCondition.Check( evidence ))
{
CodeGroup retGroup = this.Copy();
retGroup.Children = new ArrayList();
IEnumerator enumerator = this.Children.GetEnumerator();
while (enumerator.MoveNext())
{
CodeGroup matchingGroups = ((CodeGroup)enumerator.Current).ResolveMatchingCodeGroups( evidence );
// If the child has a policy, we are done.
if (matchingGroups != null)
{
retGroup.AddChild( matchingGroups );
break;
}
}
return retGroup;
}
else
{
return null;
}
}
public override CodeGroup Copy()
{
FirstMatchCodeGroup group = new FirstMatchCodeGroup();
group.MembershipCondition = this.MembershipCondition;
group.PolicyStatement = this.PolicyStatement;
group.Name = this.Name;
group.Description = this.Description;
IEnumerator enumerator = this.Children.GetEnumerator();
while (enumerator.MoveNext())
{
group.AddChild( (CodeGroup)enumerator.Current );
}
return group;
}
public override String MergeLogic
{
get
{
return Environment.GetResourceString( "MergeLogic_FirstMatch" );
}
}
internal override String GetTypeName()
{
return "System.Security.Policy.FirstMatchCodeGroup";
}
}
}

View File

@@ -0,0 +1,68 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// GacInstalled is an IIdentity representing whether or not an assembly is installed in the Gac
//
namespace System.Security.Policy {
using System.Runtime.Remoting;
using System;
using System.Security;
using System.Security.Util;
using System.IO;
using System.Collections;
using GacIdentityPermission = System.Security.Permissions.GacIdentityPermission;
using System.Runtime.CompilerServices;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GacInstalled : EvidenceBase, IIdentityPermissionFactory
{
public GacInstalled()
{
}
public IPermission CreateIdentityPermission( Evidence evidence )
{
return new GacIdentityPermission();
}
public override bool Equals(Object o)
{
return o is GacInstalled;
}
public override int GetHashCode()
{
return 0;
}
public override EvidenceBase Clone()
{
return new GacInstalled();
}
public Object Copy()
{
return Clone();
}
internal SecurityElement ToXml()
{
SecurityElement elem = new SecurityElement( this.GetType().FullName );
elem.AddAttribute( "version", "1" );
return elem;
}
public override String ToString()
{
return ToXml().ToString();
}
}
}

View File

@@ -0,0 +1,108 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// GacMembershipCondition.cs
//
// Implementation of membership condition for being in the Gac
//
namespace System.Security.Policy {
using System;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class GacMembershipCondition : IMembershipCondition, IConstantMembershipCondition, IReportMatchMembershipCondition
{
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
//
//------------------------------------------------------
public GacMembershipCondition()
{
}
//------------------------------------------------------
//
// IMEMBERSHIPCONDITION IMPLEMENTATION
//
//------------------------------------------------------
public bool Check( Evidence evidence )
{
object usedEvidence = null;
return (this as IReportMatchMembershipCondition).Check(evidence, out usedEvidence);
}
bool IReportMatchMembershipCondition.Check(Evidence evidence, out object usedEvidence)
{
usedEvidence = null;
if (evidence == null)
return false;
return evidence.GetHostEvidence<GacInstalled>() != null;
}
public IMembershipCondition Copy()
{
return new GacMembershipCondition();
}
public SecurityElement ToXml()
{
return ToXml( null );
}
public void FromXml( SecurityElement e )
{
FromXml( e, null );
}
public SecurityElement ToXml( PolicyLevel level )
{
SecurityElement root = new SecurityElement( "IMembershipCondition" );
System.Security.Util.XMLUtil.AddClassAttribute( root, this.GetType(), this.GetType().FullName );
root.AddAttribute( "version", "1" );
return root;
}
public void FromXml( SecurityElement e, PolicyLevel level )
{
if (e == null)
throw new ArgumentNullException("e");
if (!e.Tag.Equals( "IMembershipCondition" ))
throw new ArgumentException( Environment.GetResourceString( "Argument_MembershipConditionElement" ) );
Contract.EndContractBlock();
}
public override bool Equals( Object o )
{
GacMembershipCondition that = (o as GacMembershipCondition);
if (that != null)
return true;
return false;
}
public override int GetHashCode()
{
return 0;
}
public override String ToString()
{
return Environment.GetResourceString( "GAC_ToString" );
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,305 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// HashMembershipCondition.cs
//
// Implementation of membership condition for hashes of assemblies.
//
namespace System.Security.Policy {
using System.Collections;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Util;
using System.Security.Permissions;
using System.Threading;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class HashMembershipCondition : ISerializable, IDeserializationCallback, IMembershipCondition, IReportMatchMembershipCondition {
private byte[] m_value = null;
private HashAlgorithm m_hashAlg = null;
private SecurityElement m_element = null;
private object s_InternalSyncObject = null;
private object InternalSyncObject {
get {
if (s_InternalSyncObject == null) {
Object o = new Object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
internal HashMembershipCondition() {}
private HashMembershipCondition (SerializationInfo info, StreamingContext context) {
m_value = (byte[]) info.GetValue("HashValue", typeof(byte[]));
string hashAlgorithm = (string) info.GetValue("HashAlgorithm", typeof(string));
if (hashAlgorithm != null)
m_hashAlg = HashAlgorithm.Create(hashAlgorithm);
else
m_hashAlg = new SHA1Managed();
}
public HashMembershipCondition(HashAlgorithm hashAlg, byte[] value) {
if (value == null)
throw new ArgumentNullException("value");
if (hashAlg == null)
throw new ArgumentNullException("hashAlg");
Contract.EndContractBlock();
m_value = new byte[value.Length];
Array.Copy(value, m_value, value.Length);
m_hashAlg = hashAlg;
}
/// <internalonly/>
[System.Security.SecurityCritical]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("HashValue", this.HashValue);
info.AddValue("HashAlgorithm", this.HashAlgorithm.ToString());
}
/// <internalonly/>
void IDeserializationCallback.OnDeserialization (Object sender) {}
public HashAlgorithm HashAlgorithm {
set {
if (value == null)
throw new ArgumentNullException("HashAlgorithm");
Contract.EndContractBlock();
m_hashAlg = value;
}
get {
if (m_hashAlg == null && m_element != null)
ParseHashAlgorithm();
return m_hashAlg;
}
}
public byte[] HashValue {
set {
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
m_value = new byte[value.Length];
Array.Copy(value, m_value, value.Length);
}
get {
if (m_value == null && m_element != null)
ParseHashValue();
if (m_value == null)
return null;
byte[] value = new byte[m_value.Length];
Array.Copy(m_value, value, m_value.Length);
return value;
}
}
public bool Check(Evidence evidence) {
object usedEvidence = null;
return (this as IReportMatchMembershipCondition).Check(evidence, out usedEvidence);
}
bool IReportMatchMembershipCondition.Check(Evidence evidence, out object usedEvidence) {
usedEvidence = null;
if (evidence == null)
return false;
Hash hash = evidence.GetHostEvidence<Hash>();
if (hash != null) {
if (m_value == null && m_element != null)
ParseHashValue();
if (m_hashAlg == null && m_element != null)
ParseHashAlgorithm();
byte[] asmHash = null;
lock (InternalSyncObject) {
asmHash = hash.GenerateHash(m_hashAlg);
}
if (asmHash != null && CompareArrays(asmHash, m_value)) {
usedEvidence = hash;
return true;
}
}
return false;
}
public IMembershipCondition Copy() {
if (m_value == null && m_element != null)
ParseHashValue();
if (m_hashAlg == null && m_element != null)
ParseHashAlgorithm();
return new HashMembershipCondition(m_hashAlg, m_value);
}
public SecurityElement ToXml() {
return ToXml(null);
}
public void FromXml(SecurityElement e) {
FromXml(e, null);
}
public SecurityElement ToXml(PolicyLevel level) {
if (m_value == null && m_element != null)
ParseHashValue();
if (m_hashAlg == null && m_element != null)
ParseHashAlgorithm();
SecurityElement root = new SecurityElement("IMembershipCondition");
XMLUtil.AddClassAttribute(root, this.GetType(), "System.Security.Policy.HashMembershipCondition");
// If you hit this assert then most likely you are trying to change the name of this class.
// This is ok as long as you change the hard coded string above and change the assert below.
Contract.Assert(this.GetType().FullName.Equals("System.Security.Policy.HashMembershipCondition"), "Class name changed!");
root.AddAttribute("version", "1");
if (m_value != null)
root.AddAttribute(s_tagHashValue, Hex.EncodeHexString(HashValue));
if (m_hashAlg != null)
root.AddAttribute(s_tagHashAlgorithm, HashAlgorithm.GetType().FullName);
return root;
}
public void FromXml(SecurityElement e, PolicyLevel level) {
if (e == null)
throw new ArgumentNullException("e");
if (!e.Tag.Equals("IMembershipCondition"))
throw new ArgumentException(Environment.GetResourceString("Argument_MembershipConditionElement"));
Contract.EndContractBlock();
lock (InternalSyncObject) {
m_element = e;
m_value = null;
m_hashAlg = null;
}
}
public override bool Equals(Object o) {
HashMembershipCondition that = (o as HashMembershipCondition);
if (that != null) {
if (this.m_hashAlg == null && this.m_element != null)
this.ParseHashAlgorithm();
if (that.m_hashAlg == null && that.m_element != null)
that.ParseHashAlgorithm();
if (this.m_hashAlg != null && that.m_hashAlg != null &&
this.m_hashAlg.GetType() == that.m_hashAlg.GetType()) {
if (this.m_value == null && this.m_element != null)
this.ParseHashValue();
if (that.m_value == null && that.m_element != null)
that.ParseHashValue();
if (this.m_value.Length != that.m_value.Length)
return false;
for (int i = 0; i < m_value.Length; i++) {
if (this.m_value[i] != that.m_value[i])
return false;
}
return true;
}
}
return false;
}
public override int GetHashCode() {
if (this.m_hashAlg == null && this.m_element != null)
this.ParseHashAlgorithm();
int accumulator = this.m_hashAlg != null ? this.m_hashAlg.GetType().GetHashCode() : 0;
if (this.m_value == null && this.m_element != null)
this.ParseHashValue();
accumulator = accumulator ^ GetByteArrayHashCode(this.m_value);
return accumulator;
}
public override string ToString() {
if (m_hashAlg == null)
ParseHashAlgorithm();
return Environment.GetResourceString("Hash_ToString", m_hashAlg.GetType().AssemblyQualifiedName, Hex.EncodeHexString(HashValue));
}
private const string s_tagHashValue = "HashValue";
private const string s_tagHashAlgorithm = "HashAlgorithm";
private void ParseHashValue() {
lock (InternalSyncObject) {
if (m_element == null)
return;
string elHash = m_element.Attribute(s_tagHashValue);
if (elHash != null)
m_value = Hex.DecodeHexString(elHash);
else
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXMLElement", s_tagHashValue, this.GetType().FullName));
if (m_value != null && m_hashAlg != null) {
m_element = null;
}
}
}
private void ParseHashAlgorithm() {
lock (InternalSyncObject) {
if (m_element == null)
return;
string elHashAlg = m_element.Attribute(s_tagHashAlgorithm);
if (elHashAlg != null)
m_hashAlg = HashAlgorithm.Create(elHashAlg);
else
m_hashAlg = new SHA1Managed();
if (m_value != null && m_hashAlg != null)
m_element = null;
}
}
private static bool CompareArrays(byte[] first, byte[] second) {
if (first.Length != second.Length)
return false;
int count = first.Length;
for (int i = 0; i < count; ++i) {
if (first[i] != second[i])
return false;
}
return true;
}
private static int GetByteArrayHashCode(byte[] baData) {
if (baData == null)
return 0;
int accumulator = 0;
for (int i = 0; i < baData.Length; ++i) {
accumulator = (accumulator << 8) ^ (int)baData[i] ^ (accumulator >> 24);
}
return accumulator;
}
}
}

View File

@@ -0,0 +1,114 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// IApplicationTrustManager.cs
//
namespace System.Security.Policy {
//
// Interface that defines an IApplicationTrustManager. An IApplicationTrustManager handles application security decisions
// when there is no stored policy for that app, be this by prompting the user, checking a web service, or other means.
//
[System.Runtime.InteropServices.ComVisible(true)]
public interface IApplicationTrustManager : ISecurityEncodable {
ApplicationTrust DetermineApplicationTrust (ActivationContext activationContext, TrustManagerContext context);
}
//
// This enumeration provides a hint to the trust manager as to the UI it should provide for the trust decision.
//
[System.Runtime.InteropServices.ComVisible(true)]
public enum TrustManagerUIContext {
Install,
Upgrade,
Run
}
//
// The TrustManagerContext class represents context that the host would like the Trust Manager to consider when making
// a run/no-run decision and when setting up the security on a new AppDomain in which to run an application.
// This class can be extended by trust managers so it is non-sealed.
//
[System.Runtime.InteropServices.ComVisible(true)]
public class TrustManagerContext {
private bool m_ignorePersistedDecision;
private TrustManagerUIContext m_uiContext;
private bool m_noPrompt;
private bool m_keepAlive;
private bool m_persist;
private ApplicationIdentity m_appId;
public TrustManagerContext () : this (TrustManagerUIContext.Run) {}
public TrustManagerContext (TrustManagerUIContext uiContext) {
m_ignorePersistedDecision = false;
m_uiContext = uiContext;
m_keepAlive = false;
m_persist = true;
}
public virtual TrustManagerUIContext UIContext {
get {
return m_uiContext;
}
set {
m_uiContext = value;
}
}
public virtual bool NoPrompt {
get {
return m_noPrompt;
}
set {
m_noPrompt = value;
}
}
public virtual bool IgnorePersistedDecision {
get {
return m_ignorePersistedDecision;
}
set {
m_ignorePersistedDecision = value;
}
}
public virtual bool KeepAlive {
get {
return m_keepAlive;
}
set {
m_keepAlive = value;
}
}
public virtual bool Persist {
get {
return m_persist;
}
set {
m_persist = value;
}
}
public virtual ApplicationIdentity PreviousApplicationIdentity {
get {
return m_appId;
}
set {
m_appId = value;
}
}
}
}

View File

@@ -0,0 +1,20 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// IConstantMembershipCondition.cs
//
// <OWNER>[....]</OWNER>
//
// Interface that all constant membership conditions must implement
//
namespace System.Security.Policy {
using System;
internal interface IConstantMembershipCondition
{
}
}

Some files were not shown because too many files have changed in this diff Show More