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,43 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
public class ClaimTypeRequirement
{
internal const bool DefaultIsOptional = false;
string claimType;
bool isOptional;
public ClaimTypeRequirement(string claimType)
: this(claimType, DefaultIsOptional)
{
}
public ClaimTypeRequirement(string claimType, bool isOptional)
{
if (claimType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claimType");
}
if (claimType.Length <= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("claimType", SR.GetString(SR.ClaimTypeCannotBeEmpty));
}
this.claimType = claimType;
this.isOptional = isOptional;
}
public string ClaimType
{
get { return this.claimType; }
}
public bool IsOptional
{
get { return this.isOptional; }
}
}
}

View File

@@ -0,0 +1,297 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System.Collections;
using System.ServiceModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
sealed class DerivedKeySecurityToken : SecurityToken
{
// public const string DefaultLabel = "WS-SecureConversationWS-SecureConversation";
static readonly byte[] DefaultLabel = new byte[]
{
(byte)'W', (byte)'S', (byte)'-', (byte)'S', (byte)'e', (byte)'c', (byte)'u', (byte)'r', (byte)'e',
(byte)'C', (byte)'o', (byte)'n', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'a', (byte)'t', (byte)'i', (byte)'o', (byte)'n',
(byte)'W', (byte)'S', (byte)'-', (byte)'S', (byte)'e', (byte)'c', (byte)'u', (byte)'r', (byte)'e',
(byte)'C', (byte)'o', (byte)'n', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'a', (byte)'t', (byte)'i', (byte)'o', (byte)'n'
};
public const int DefaultNonceLength = 16;
public const int DefaultDerivedKeyLength = 32;
string id;
byte[] key;
string keyDerivationAlgorithm;
string label;
int length = -1;
byte[] nonce;
// either offset or generation must be specified.
int offset = -1;
int generation = -1;
SecurityToken tokenToDerive;
SecurityKeyIdentifierClause tokenToDeriveIdentifier;
ReadOnlyCollection<SecurityKey> securityKeys;
// create from scratch
public DerivedKeySecurityToken(SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, int length)
: this(tokenToDerive, tokenToDeriveIdentifier, length, SecurityUtils.GenerateId())
{
}
internal DerivedKeySecurityToken(SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier,
int length, string id)
{
if (length != 16 && length != 24 && length != 32)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.Psha1KeyLengthInvalid, length * 8)));
byte[] nonce = new byte[DefaultNonceLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(nonce);
Initialize(id, -1, 0, length, null, nonce, tokenToDerive, tokenToDeriveIdentifier, SecurityAlgorithms.Psha1KeyDerivation);
}
internal DerivedKeySecurityToken(int generation, int offset, int length,
string label, int minNonceLength, SecurityToken tokenToDerive,
SecurityKeyIdentifierClause tokenToDeriveIdentifier,
string derivationAlgorithm, string id)
{
byte[] nonce = new byte[minNonceLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(nonce);
Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm);
}
// create from xml
internal DerivedKeySecurityToken(int generation, int offset, int length,
string label, byte[] nonce, SecurityToken tokenToDerive,
SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm, string id)
{
Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm, false);
}
public override string Id
{
get { return this.id; }
}
public override DateTime ValidFrom
{
get { return this.tokenToDerive.ValidFrom; }
}
public override DateTime ValidTo
{
get { return this.tokenToDerive.ValidTo; }
}
public string KeyDerivationAlgorithm
{
get { return keyDerivationAlgorithm; }
}
public int Generation
{
get { return this.generation; }
}
public string Label
{
get { return this.label; }
}
public int Length
{
get { return this.length; }
}
internal byte[] Nonce
{
get { return this.nonce; }
}
public int Offset
{
get { return this.offset; }
}
internal SecurityToken TokenToDerive
{
get { return this.tokenToDerive; }
}
internal SecurityKeyIdentifierClause TokenToDeriveIdentifier
{
get { return this.tokenToDeriveIdentifier; }
}
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
if (this.securityKeys == null)
{
#pragma warning suppress 56503
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DerivedKeyNotInitialized)));
}
return this.securityKeys;
}
}
public byte[] GetKeyBytes()
{
return SecurityUtils.CloneBuffer(this.key);
}
public byte[] GetNonce()
{
return SecurityUtils.CloneBuffer(this.nonce);
}
internal bool TryGetSecurityKeys(out ReadOnlyCollection<SecurityKey> keys)
{
keys = this.securityKeys;
return (keys != null);
}
public override string ToString()
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
writer.WriteLine("DerivedKeySecurityToken:");
writer.WriteLine(" Generation: {0}", this.Generation);
writer.WriteLine(" Offset: {0}", this.Offset);
writer.WriteLine(" Length: {0}", this.Length);
writer.WriteLine(" Label: {0}", this.Label);
writer.WriteLine(" Nonce: {0}", Convert.ToBase64String(this.Nonce));
writer.WriteLine(" TokenToDeriveFrom:");
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
SecurityStandardsManager.DefaultInstance.SecurityTokenSerializer.WriteKeyIdentifierClause(XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter), this.TokenToDeriveIdentifier);
}
return writer.ToString();
}
void Initialize(string id, int generation, int offset, int length, string label, byte[] nonce,
SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm)
{
Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm, true);
}
void Initialize(string id, int generation, int offset, int length, string label, byte[] nonce,
SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm,
bool initializeDerivedKey)
{
if (id == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");
}
if (tokenToDerive == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenToDerive");
}
if (tokenToDeriveIdentifier == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokentoDeriveIdentifier");
}
if (!SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, tokenToDerive))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.DerivedKeyCannotDeriveFromSecret)));
}
if (nonce == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("nonce");
}
if (length == -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("length"));
}
if (offset == -1 && generation == -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyPosAndGenNotSpecified));
}
if (offset >= 0 && generation >= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyPosAndGenBothSpecified));
}
this.id = id;
this.label = label;
this.nonce = nonce;
this.length = length;
this.offset = offset;
this.generation = generation;
this.tokenToDerive = tokenToDerive;
this.tokenToDeriveIdentifier = tokenToDeriveIdentifier;
this.keyDerivationAlgorithm = derivationAlgorithm;
if (initializeDerivedKey)
{
InitializeDerivedKey(this.length);
}
}
internal void InitializeDerivedKey(int maxKeyLength)
{
if (this.key != null)
{
return;
}
if (this.length > maxKeyLength)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyLengthTooLong, this.length, maxKeyLength));
}
this.key = SecurityUtils.GenerateDerivedKey(this.tokenToDerive, this.keyDerivationAlgorithm,
(this.label != null ? Encoding.UTF8.GetBytes(this.label) : DefaultLabel), this.nonce, this.length * 8,
((this.offset >= 0) ? this.offset : this.generation * this.length));
if ((this.key == null) || (this.key.Length == 0))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.DerivedKeyCannotDeriveFromSecret));
}
List<SecurityKey> temp = new List<SecurityKey>(1);
temp.Add(new InMemorySymmetricSecurityKey(this.key, false));
this.securityKeys = temp.AsReadOnly();
}
internal void InitializeDerivedKey(ReadOnlyCollection<SecurityKey> securityKeys)
{
this.key = ((SymmetricSecurityKey)securityKeys[0]).GetSymmetricKey();
this.securityKeys = securityKeys;
}
internal static void EnsureAcceptableOffset(int offset, int generation, int length, int maxOffset)
{
if (offset != -1)
{
if (offset > maxOffset)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.DerivedKeyTokenOffsetTooHigh, offset, maxOffset)));
}
}
else
{
int effectiveOffset = generation * length;
if ((effectiveOffset < generation && effectiveOffset < length) || effectiveOffset > maxOffset)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.DerivedKeyTokenGenerationAndLengthTooHigh, generation, length, maxOffset)));
}
}
}
}
}

View File

@@ -0,0 +1,74 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IdentityModel.Tokens;
sealed class DerivedKeySecurityTokenStub : SecurityToken
{
string id;
string derivationAlgorithm;
string label;
int length;
byte[] nonce;
int offset;
int generation;
SecurityKeyIdentifierClause tokenToDeriveIdentifier;
public DerivedKeySecurityTokenStub(int generation, int offset, int length,
string label, byte[] nonce,
SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm, string id)
{
this.id = id;
this.generation = generation;
this.offset = offset;
this.length = length;
this.label = label;
this.nonce = nonce;
this.tokenToDeriveIdentifier = tokenToDeriveIdentifier;
this.derivationAlgorithm = derivationAlgorithm;
}
public override string Id
{
get { return this.id; }
}
public override DateTime ValidFrom
{
#pragma warning suppress 56503 // Property does not make sense for Derived Key tokens.
get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException()); }
}
public override DateTime ValidTo
{
#pragma warning suppress 56503 // Property does not make sense for Derived Key tokens.
get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException()); }
}
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get { return null; }
}
public SecurityKeyIdentifierClause TokenToDeriveIdentifier
{
get { return this.tokenToDeriveIdentifier; }
}
public DerivedKeySecurityToken CreateToken(SecurityToken tokenToDerive, int maxKeyLength)
{
DerivedKeySecurityToken result = new DerivedKeySecurityToken(this.generation, this.offset, this.length,
this.label, this.nonce, tokenToDerive, this.tokenToDeriveIdentifier, this.derivationAlgorithm, this.Id);
result.InitializeDerivedKey(maxKeyLength);
return result;
}
}
}

View File

@@ -0,0 +1,31 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IdentityModel.Policy;
class GenericXmlSecurityTokenAuthenticator : SecurityTokenAuthenticator
{
public GenericXmlSecurityTokenAuthenticator()
: base()
{ }
protected override bool CanValidateTokenCore(SecurityToken token)
{
return (token is GenericXmlSecurityToken);
}
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
{
GenericXmlSecurityToken gxt = (GenericXmlSecurityToken)token;
return gxt.AuthorizationPolicies;
}
}
}

View File

@@ -0,0 +1,19 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System;
using System.Xml;
using System.IdentityModel.Tokens;
public delegate void IssuedSecurityTokenHandler(SecurityToken issuedToken, EndpointAddress tokenRequestor);
public delegate void RenewedSecurityTokenHandler(SecurityToken newSecurityToken, SecurityToken oldSecurityToken);
public interface IIssuanceSecurityTokenAuthenticator
{
IssuedSecurityTokenHandler IssuedSecurityTokenHandler { get; set; }
RenewedSecurityTokenHandler RenewedSecurityTokenHandler { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System;
using System.Xml;
using System.Collections.ObjectModel;
public interface ISecurityContextSecurityTokenCache
{
void AddContext(SecurityContextSecurityToken token);
bool TryAddContext(SecurityContextSecurityToken token);
void ClearContexts();
void RemoveContext(UniqueId contextId, UniqueId generation);
void RemoveAllContexts(UniqueId contextId);
SecurityContextSecurityToken GetContext(UniqueId contextId, UniqueId generation);
Collection<SecurityContextSecurityToken> GetAllContexts(UniqueId contextId);
void UpdateContextCachingTime(SecurityContextSecurityToken context, DateTime expirationTime);
}
}

View File

@@ -0,0 +1,11 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
interface ISecurityContextSecurityTokenCacheProvider
{
ISecurityContextSecurityTokenCache TokenCache { get; }
}
}

View File

@@ -0,0 +1,92 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.ServiceModel;
using System.Xml;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Globalization;
using System.Net;
namespace System.ServiceModel.Security.Tokens
{
public sealed class InitiatorServiceModelSecurityTokenRequirement : ServiceModelSecurityTokenRequirement
{
WebHeaderCollection webHeaderCollection;
public InitiatorServiceModelSecurityTokenRequirement()
: base()
{
Properties.Add(IsInitiatorProperty, (object)true);
}
public EndpointAddress TargetAddress
{
get
{
return GetPropertyOrDefault<EndpointAddress>(TargetAddressProperty, null);
}
set
{
this.Properties[TargetAddressProperty] = value;
}
}
public Uri Via
{
get
{
return GetPropertyOrDefault<Uri>(ViaProperty, null);
}
set
{
this.Properties[ViaProperty] = value;
}
}
internal bool IsOutOfBandToken
{
get
{
return GetPropertyOrDefault<bool>(IsOutOfBandTokenProperty, false);
}
set
{
this.Properties[IsOutOfBandTokenProperty] = value;
}
}
internal bool PreferSslCertificateAuthenticator
{
get
{
return GetPropertyOrDefault<bool>(PreferSslCertificateAuthenticatorProperty, false);
}
set
{
this.Properties[PreferSslCertificateAuthenticatorProperty] = value;
}
}
internal WebHeaderCollection WebHeaders
{
get
{
return this.webHeaderCollection;
}
set
{
this.webHeaderCollection = value;
}
}
public override string ToString()
{
return InternalToString();
}
}
}

View File

@@ -0,0 +1,37 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IdentityModel.Policy;
using System.IdentityModel.Claims;
using System.Security.Principal;
class KerberosRequestorSecurityTokenAuthenticator : SecurityTokenAuthenticator
{
public KerberosRequestorSecurityTokenAuthenticator()
: base()
{ }
protected override bool CanValidateTokenCore(SecurityToken token)
{
return (token is KerberosRequestorSecurityToken);
}
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
{
KerberosRequestorSecurityToken kerbToken = (KerberosRequestorSecurityToken) token;
List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
ClaimSet claimSet = new DefaultClaimSet(ClaimSet.System, new Claim(ClaimTypes.Spn, kerbToken.ServicePrincipalName, Rights.PossessProperty));
policies.Add(new UnconditionalPolicy(SecurityUtils.CreateIdentity(kerbToken.ServicePrincipalName, SecurityUtils.AuthTypeKerberos), claimSet));
return policies.AsReadOnly();
}
}
}

View File

@@ -0,0 +1,49 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System.ServiceModel.Security;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
public class KerberosSecurityTokenParameters : SecurityTokenParameters
{
protected KerberosSecurityTokenParameters(KerberosSecurityTokenParameters other)
: base(other)
{
// empty
}
public KerberosSecurityTokenParameters()
: base()
{
this.InclusionMode = SecurityTokenInclusionMode.Once;
}
internal protected override bool HasAsymmetricKey { get { return false; } }
internal protected override bool SupportsClientAuthentication { get { return true; } }
internal protected override bool SupportsServerAuthentication { get { return true; } }
internal protected override bool SupportsClientWindowsIdentity { get { return true; } }
protected override SecurityTokenParameters CloneCore()
{
return new KerberosSecurityTokenParameters(this);
}
internal protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
{
return base.CreateKeyIdentifierClause<KerberosTicketHashKeyIdentifierClause, LocalIdKeyIdentifierClause>(token, referenceStyle);
}
protected internal override void InitializeSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
requirement.TokenType = SecurityTokenTypes.Kerberos;
requirement.KeyType = SecurityKeyType.SymmetricKey;
requirement.RequireCryptographicToken = true;
}
}
}

View File

@@ -0,0 +1,30 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IdentityModel.Policy;
class NonValidatingSecurityTokenAuthenticator<TTokenType> : SecurityTokenAuthenticator
{
public NonValidatingSecurityTokenAuthenticator()
: base()
{ }
protected override bool CanValidateTokenCore(SecurityToken token)
{
return (token is TTokenType);
}
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
{
return EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
}
}
}

View File

@@ -0,0 +1,155 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.Security.Cryptography;
using System.Security.Authentication.ExtendedProtection;
using System.ServiceModel.Diagnostics;
namespace System.ServiceModel.Security.Tokens
{
/// <summary>
/// The ProviderBackedSecurityToken was added for the ChannelBindingToken work for Win7.
/// It is used to delay the resolution of a token until it is needed.
/// For the CBT, this delay is necessary as the CBT is not available until SecurityAppliedMessage.OnWriteMessage is called.
/// The CBT binds a token to the
/// </summary>
internal class ProviderBackedSecurityToken : SecurityToken
{
SecurityTokenProvider _tokenProvider;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile SecurityToken _securityToken;
TimeSpan _timeout;
ChannelBinding _channelBinding;
object _lock;
/// <summary>
/// Constructor to create an instance of this class.
/// </summary>
/// <param name="securityToken">SecurityToken that represents the SecurityTokenElement element.</param>
public ProviderBackedSecurityToken( SecurityTokenProvider tokenProvider, TimeSpan timeout )
{
_lock = new object();
if ( tokenProvider == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("tokenProvider"));
}
_tokenProvider = tokenProvider;
_timeout = timeout;
}
public SecurityTokenProvider TokenProvider
{
get { return _tokenProvider; }
}
public ChannelBinding ChannelBinding
{
set { _channelBinding = value; }
}
void ResolveSecurityToken()
{
if ( _securityToken == null )
{
lock ( _lock )
{
if ( _securityToken == null )
{
ClientCredentialsSecurityTokenManager.KerberosSecurityTokenProviderWrapper kerbTokenProvider = _tokenProvider
as ClientCredentialsSecurityTokenManager.KerberosSecurityTokenProviderWrapper;
if (kerbTokenProvider != null)
{
_securityToken = kerbTokenProvider.GetToken((new TimeoutHelper(_timeout)).RemainingTime(), _channelBinding);
}
else
{
_securityToken = _tokenProvider.GetToken((new TimeoutHelper(_timeout)).RemainingTime());
}
}
}
}
if ( _securityToken == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityTokenException( SR.GetString( SR.SecurityTokenNotResolved, _tokenProvider.GetType().ToString() ) ) );
}
return;
}
public SecurityToken Token
{
get
{
if ( _securityToken == null )
{
ResolveSecurityToken();
}
return _securityToken;
}
}
public override string Id
{
get
{
if ( _securityToken == null )
{
ResolveSecurityToken();
}
return _securityToken.Id;
}
}
public override System.Collections.ObjectModel.ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
if ( _securityToken == null )
{
ResolveSecurityToken();
}
return _securityToken.SecurityKeys;
}
}
public override DateTime ValidFrom
{
get
{
if ( _securityToken == null )
{
ResolveSecurityToken();
}
return _securityToken.ValidFrom;
}
}
public override DateTime ValidTo
{
get
{
if ( _securityToken == null )
{
ResolveSecurityToken();
}
return _securityToken.ValidTo;
}
}
}
}

View File

@@ -0,0 +1,80 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Xml;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Globalization;
namespace System.ServiceModel.Security.Tokens
{
public sealed class RecipientServiceModelSecurityTokenRequirement : ServiceModelSecurityTokenRequirement
{
public RecipientServiceModelSecurityTokenRequirement()
: base()
{
Properties.Add(IsInitiatorProperty, (object)false);
}
public Uri ListenUri
{
get
{
return GetPropertyOrDefault<Uri>(ListenUriProperty, null);
}
set
{
this.Properties[ListenUriProperty] = value;
}
}
public AuditLogLocation AuditLogLocation
{
get
{
return GetPropertyOrDefault<AuditLogLocation>(AuditLogLocationProperty, ServiceSecurityAuditBehavior.defaultAuditLogLocation);
}
set
{
this.Properties[AuditLogLocationProperty] = value;
}
}
public bool SuppressAuditFailure
{
get
{
return GetPropertyOrDefault<bool>(SuppressAuditFailureProperty, ServiceSecurityAuditBehavior.defaultSuppressAuditFailure);
}
set
{
this.Properties[SuppressAuditFailureProperty] = value;
}
}
public AuditLevel MessageAuthenticationAuditLevel
{
get
{
return GetPropertyOrDefault<AuditLevel>(MessageAuthenticationAuditLevelProperty, ServiceSecurityAuditBehavior.defaultMessageAuthenticationAuditLevel);
}
set
{
this.Properties[MessageAuthenticationAuditLevelProperty] = value;
}
}
public override string ToString()
{
return InternalToString();
}
}
}

View File

@@ -0,0 +1,55 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <copyright file="UserNameSecurityTokenParameters.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System.ServiceModel.Security;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
public class RsaSecurityTokenParameters : SecurityTokenParameters
{
protected RsaSecurityTokenParameters(RsaSecurityTokenParameters other)
: base(other)
{
this.InclusionMode = SecurityTokenInclusionMode.Never;
}
public RsaSecurityTokenParameters()
: base()
{
this.InclusionMode = SecurityTokenInclusionMode.Never;
}
internal protected override bool HasAsymmetricKey { get { return true; } }
internal protected override bool SupportsClientAuthentication { get { return true; } }
internal protected override bool SupportsServerAuthentication { get { return true; } }
internal protected override bool SupportsClientWindowsIdentity { get { return false; } }
protected override SecurityTokenParameters CloneCore()
{
return new RsaSecurityTokenParameters(this);
}
internal protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
{
return this.CreateKeyIdentifierClause<RsaKeyIdentifierClause, RsaKeyIdentifierClause>(token, referenceStyle);
}
protected internal override void InitializeSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
requirement.TokenType = SecurityTokenTypes.Rsa;
requirement.RequireCryptographicToken = true;
requirement.KeyType = SecurityKeyType.AsymmetricKey;
}
}
}

View File

@@ -0,0 +1,226 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System.IdentityModel.Tokens;
using System.ServiceModel.Channels;
using System.IdentityModel.Selectors;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Text;
using System.Globalization;
public class SecureConversationSecurityTokenParameters : SecurityTokenParameters
{
internal const bool defaultRequireCancellation = true;
internal const bool defaultCanRenewSession = true;
SecurityBindingElement bootstrapSecurityBindingElement;
ChannelProtectionRequirements bootstrapProtectionRequirements;
bool requireCancellation;
bool canRenewSession = defaultCanRenewSession;
BindingContext issuerBindingContext;
protected SecureConversationSecurityTokenParameters(SecureConversationSecurityTokenParameters other)
: base(other)
{
this.requireCancellation = other.requireCancellation;
this.canRenewSession = other.canRenewSession;
if (other.bootstrapSecurityBindingElement != null)
this.bootstrapSecurityBindingElement = (SecurityBindingElement)other.bootstrapSecurityBindingElement.Clone();
if (other.bootstrapProtectionRequirements != null)
this.bootstrapProtectionRequirements = new ChannelProtectionRequirements(other.bootstrapProtectionRequirements);
if (other.issuerBindingContext != null)
this.issuerBindingContext = other.issuerBindingContext.Clone();
}
public SecureConversationSecurityTokenParameters()
: this(null, defaultRequireCancellation, null)
{
// empty
}
public SecureConversationSecurityTokenParameters(SecurityBindingElement bootstrapSecurityBindingElement)
: this(bootstrapSecurityBindingElement, defaultRequireCancellation, null)
{
// empty
}
public SecureConversationSecurityTokenParameters(SecurityBindingElement bootstrapSecurityBindingElement, bool requireCancellation)
: this(bootstrapSecurityBindingElement, requireCancellation, true)
{
// empty
}
public SecureConversationSecurityTokenParameters(SecurityBindingElement bootstrapSecurityBindingElement, bool requireCancellation, bool canRenewSession)
: this(bootstrapSecurityBindingElement, requireCancellation, canRenewSession, null)
{
// empty
}
public SecureConversationSecurityTokenParameters(SecurityBindingElement bootstrapSecurityBindingElement, bool requireCancellation, ChannelProtectionRequirements bootstrapProtectionRequirements)
: this(bootstrapSecurityBindingElement, requireCancellation, defaultCanRenewSession, null)
{
// empty
}
public SecureConversationSecurityTokenParameters(SecurityBindingElement bootstrapSecurityBindingElement, bool requireCancellation, bool canRenewSession, ChannelProtectionRequirements bootstrapProtectionRequirements)
: base()
{
this.bootstrapSecurityBindingElement = bootstrapSecurityBindingElement;
this.canRenewSession = canRenewSession;
if (bootstrapProtectionRequirements != null)
this.bootstrapProtectionRequirements = new ChannelProtectionRequirements(bootstrapProtectionRequirements);
else
{
this.bootstrapProtectionRequirements = new ChannelProtectionRequirements();
this.bootstrapProtectionRequirements.IncomingEncryptionParts.AddParts(new MessagePartSpecification(true));
this.bootstrapProtectionRequirements.IncomingSignatureParts.AddParts(new MessagePartSpecification(true));
this.bootstrapProtectionRequirements.OutgoingEncryptionParts.AddParts(new MessagePartSpecification(true));
this.bootstrapProtectionRequirements.OutgoingSignatureParts.AddParts(new MessagePartSpecification(true));
}
this.requireCancellation = requireCancellation;
}
internal protected override bool HasAsymmetricKey { get { return false; } }
public SecurityBindingElement BootstrapSecurityBindingElement
{
get
{
return this.bootstrapSecurityBindingElement;
}
set
{
this.bootstrapSecurityBindingElement = value;
}
}
public ChannelProtectionRequirements BootstrapProtectionRequirements
{
get
{
return this.bootstrapProtectionRequirements;
}
}
internal BindingContext IssuerBindingContext
{
get
{
return this.issuerBindingContext;
}
set
{
if (value != null)
{
value = value.Clone();
}
this.issuerBindingContext = value;
}
}
ISecurityCapabilities BootstrapSecurityCapabilities
{
get
{
return this.bootstrapSecurityBindingElement.GetIndividualProperty<ISecurityCapabilities>();
}
}
public bool RequireCancellation
{
get
{
return this.requireCancellation;
}
set
{
this.requireCancellation = value;
}
}
public bool CanRenewSession
{
get
{
return this.canRenewSession;
}
set
{
this.canRenewSession = value;
}
}
internal protected override bool SupportsClientAuthentication
{
get
{
return this.BootstrapSecurityCapabilities == null ? false : this.BootstrapSecurityCapabilities.SupportsClientAuthentication;
}
}
internal protected override bool SupportsServerAuthentication
{
get
{
return this.BootstrapSecurityCapabilities == null ? false : this.BootstrapSecurityCapabilities.SupportsServerAuthentication;
}
}
internal protected override bool SupportsClientWindowsIdentity
{
get
{
return this.BootstrapSecurityCapabilities == null ? false : this.BootstrapSecurityCapabilities.SupportsClientWindowsIdentity;
}
}
protected override SecurityTokenParameters CloneCore()
{
return new SecureConversationSecurityTokenParameters(this);
}
internal protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
{
if (token is GenericXmlSecurityToken)
return base.CreateGenericXmlTokenKeyIdentifierClause(token, referenceStyle);
else
return this.CreateKeyIdentifierClause<SecurityContextKeyIdentifierClause, LocalIdKeyIdentifierClause>(token, referenceStyle);
}
protected internal override void InitializeSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
requirement.TokenType = ServiceModelSecurityTokenTypes.SecureConversation;
requirement.KeyType = SecurityKeyType.SymmetricKey;
requirement.RequireCryptographicToken = true;
requirement.Properties[ServiceModelSecurityTokenRequirement.SupportSecurityContextCancellationProperty] = this.RequireCancellation;
requirement.Properties[ServiceModelSecurityTokenRequirement.SecureConversationSecurityBindingElementProperty] = this.BootstrapSecurityBindingElement;
requirement.Properties[ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty] = this.IssuerBindingContext.Clone();
requirement.Properties[ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty] = this.Clone();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "RequireCancellation: {0}", this.requireCancellation.ToString()));
if (this.bootstrapSecurityBindingElement == null)
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "BootstrapSecurityBindingElement: null"));
}
else
{
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "BootstrapSecurityBindingElement:"));
sb.AppendLine(" " + this.BootstrapSecurityBindingElement.ToString().Trim().Replace("\n", "\n "));
}
return sb.ToString().Trim();
}
}
}

View File

@@ -0,0 +1,309 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.Xml;
struct SecurityContextCookieSerializer
{
const int SupportedPersistanceVersion = 1;
SecurityStateEncoder securityStateEncoder;
IList<Type> knownTypes;
public SecurityContextCookieSerializer(SecurityStateEncoder securityStateEncoder, IList<Type> knownTypes)
{
if (securityStateEncoder == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityStateEncoder");
}
this.securityStateEncoder = securityStateEncoder;
this.knownTypes = knownTypes ?? new List<Type>();
}
SecurityContextSecurityToken DeserializeContext(byte[] serializedContext, byte[] cookieBlob, string id, XmlDictionaryReaderQuotas quotas)
{
SctClaimDictionary dictionary = SctClaimDictionary.Instance;
XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(serializedContext, 0, serializedContext.Length, dictionary, quotas, null, null);
int cookieVersion = -1;
UniqueId cookieContextId = null;
DateTime effectiveTime = SecurityUtils.MinUtcDateTime;
DateTime expiryTime = SecurityUtils.MaxUtcDateTime;
byte[] key = null;
string localId = null;
UniqueId keyGeneration = null;
DateTime keyEffectiveTime = SecurityUtils.MinUtcDateTime;
DateTime keyExpirationTime = SecurityUtils.MaxUtcDateTime;
List<ClaimSet> claimSets = null;
IList<IIdentity> identities = null;
bool isCookie = true;
reader.ReadFullStartElement(dictionary.SecurityContextSecurityToken, dictionary.EmptyString);
while (reader.IsStartElement())
{
if (reader.IsStartElement(dictionary.Version, dictionary.EmptyString))
{
cookieVersion = reader.ReadElementContentAsInt();
}
else if (reader.IsStartElement(dictionary.ContextId, dictionary.EmptyString))
{
cookieContextId = reader.ReadElementContentAsUniqueId();
}
else if (reader.IsStartElement(dictionary.Id, dictionary.EmptyString))
{
localId = reader.ReadElementContentAsString();
}
else if (reader.IsStartElement(dictionary.EffectiveTime, dictionary.EmptyString))
{
effectiveTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
}
else if (reader.IsStartElement(dictionary.ExpiryTime, dictionary.EmptyString))
{
expiryTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
}
else if (reader.IsStartElement(dictionary.Key, dictionary.EmptyString))
{
key = reader.ReadElementContentAsBase64();
}
else if (reader.IsStartElement(dictionary.KeyGeneration, dictionary.EmptyString))
{
keyGeneration = reader.ReadElementContentAsUniqueId();
}
else if (reader.IsStartElement(dictionary.KeyEffectiveTime, dictionary.EmptyString))
{
keyEffectiveTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
}
else if (reader.IsStartElement(dictionary.KeyExpiryTime, dictionary.EmptyString))
{
keyExpirationTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
}
else if (reader.IsStartElement(dictionary.Identities, dictionary.EmptyString))
{
identities = SctClaimSerializer.DeserializeIdentities(reader, dictionary, DataContractSerializerDefaults.CreateSerializer(typeof(IIdentity), this.knownTypes, int.MaxValue));
}
else if (reader.IsStartElement(dictionary.ClaimSets, dictionary.EmptyString))
{
reader.ReadStartElement();
DataContractSerializer claimSetSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(ClaimSet), this.knownTypes, int.MaxValue);
DataContractSerializer claimSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(Claim), this.knownTypes, int.MaxValue);
claimSets = new List<ClaimSet>(1);
while (reader.IsStartElement())
{
claimSets.Add(SctClaimSerializer.DeserializeClaimSet(reader, dictionary, claimSetSerializer, claimSerializer));
}
reader.ReadEndElement();
}
else if (reader.IsStartElement(dictionary.IsCookieMode, dictionary.EmptyString))
{
isCookie = reader.ReadElementString() == "1" ? true : false;
}
else
{
OnInvalidCookieFailure(SR.GetString(SR.SctCookieXmlParseError));
}
}
reader.ReadEndElement();
if (cookieVersion != SupportedPersistanceVersion)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SerializedTokenVersionUnsupported, cookieVersion)));
}
if (cookieContextId == null)
{
OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "ContextId"));
}
if (key == null || key.Length == 0)
{
OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "Key"));
}
if (localId != id)
{
OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "Id"));
}
List<IAuthorizationPolicy> authorizationPolicies;
if (claimSets != null)
{
authorizationPolicies = new List<IAuthorizationPolicy>(1);
authorizationPolicies.Add(new SctUnconditionalPolicy(identities, claimSets, expiryTime));
}
else
{
authorizationPolicies = null;
}
return new SecurityContextSecurityToken(cookieContextId, localId, key, effectiveTime, expiryTime,
authorizationPolicies != null ? authorizationPolicies.AsReadOnly() : null, isCookie, cookieBlob, keyGeneration, keyEffectiveTime, keyExpirationTime);
}
public byte[] CreateCookieFromSecurityContext(UniqueId contextId, string id, byte[] key, DateTime tokenEffectiveTime,
DateTime tokenExpirationTime, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime,
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
if (contextId == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextId");
}
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
}
MemoryStream stream = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream, SctClaimDictionary.Instance, null);
SctClaimDictionary dictionary = SctClaimDictionary.Instance;
writer.WriteStartElement(dictionary.SecurityContextSecurityToken, dictionary.EmptyString);
writer.WriteStartElement(dictionary.Version, dictionary.EmptyString);
writer.WriteValue(SupportedPersistanceVersion);
writer.WriteEndElement();
if (id != null)
writer.WriteElementString(dictionary.Id, dictionary.EmptyString, id);
XmlHelper.WriteElementStringAsUniqueId(writer, dictionary.ContextId, dictionary.EmptyString, contextId);
writer.WriteStartElement(dictionary.Key, dictionary.EmptyString);
writer.WriteBase64(key, 0, key.Length);
writer.WriteEndElement();
if (keyGeneration != null)
{
XmlHelper.WriteElementStringAsUniqueId(writer, dictionary.KeyGeneration, dictionary.EmptyString, keyGeneration);
}
XmlHelper.WriteElementContentAsInt64(writer, dictionary.EffectiveTime, dictionary.EmptyString, tokenEffectiveTime.ToUniversalTime().Ticks);
XmlHelper.WriteElementContentAsInt64(writer, dictionary.ExpiryTime, dictionary.EmptyString, tokenExpirationTime.ToUniversalTime().Ticks);
XmlHelper.WriteElementContentAsInt64(writer, dictionary.KeyEffectiveTime, dictionary.EmptyString, keyEffectiveTime.ToUniversalTime().Ticks);
XmlHelper.WriteElementContentAsInt64(writer, dictionary.KeyExpiryTime, dictionary.EmptyString, keyExpirationTime.ToUniversalTime().Ticks);
AuthorizationContext authContext = null;
if (authorizationPolicies != null)
authContext = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies);
if (authContext != null && authContext.ClaimSets.Count != 0)
{
DataContractSerializer identitySerializer = DataContractSerializerDefaults.CreateSerializer(typeof(IIdentity), this.knownTypes, int.MaxValue);
DataContractSerializer claimSetSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(ClaimSet), this.knownTypes, int.MaxValue);
DataContractSerializer claimSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(Claim), this.knownTypes, int.MaxValue);
SctClaimSerializer.SerializeIdentities(authContext, dictionary, writer, identitySerializer);
writer.WriteStartElement(dictionary.ClaimSets, dictionary.EmptyString);
for (int i = 0; i < authContext.ClaimSets.Count; i++)
{
SctClaimSerializer.SerializeClaimSet(authContext.ClaimSets[i], dictionary, writer, claimSetSerializer, claimSerializer);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
byte[] serializedContext = stream.ToArray();
return this.securityStateEncoder.EncodeSecurityState(serializedContext);
}
public SecurityContextSecurityToken CreateSecurityContextFromCookie(byte[] encodedCookie, UniqueId contextId, UniqueId generation, string id, XmlDictionaryReaderQuotas quotas)
{
byte[] cookie = null;
try
{
cookie = this.securityStateEncoder.DecodeSecurityState(encodedCookie);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
OnInvalidCookieFailure(SR.GetString(SR.SctCookieBlobDecodeFailure), e);
}
SecurityContextSecurityToken sct = DeserializeContext(cookie, encodedCookie, id, quotas);
if (sct.ContextId != contextId)
{
OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "ContextId"));
}
if (sct.KeyGeneration != generation)
{
OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "KeyGeneration"));
}
return sct;
}
internal static void OnInvalidCookieFailure(string reason)
{
OnInvalidCookieFailure(reason, null);
}
internal static void OnInvalidCookieFailure(string reason, Exception e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.InvalidSecurityContextCookie, reason), e));
}
class SctUnconditionalPolicy : IAuthorizationPolicy
{
SecurityUniqueId id = SecurityUniqueId.Create();
IList<IIdentity> identities;
IList<ClaimSet> claimSets;
DateTime expirationTime;
public SctUnconditionalPolicy(IList<IIdentity> identities, IList<ClaimSet> claimSets, DateTime expirationTime)
{
this.identities = identities;
this.claimSets = claimSets;
this.expirationTime = expirationTime;
}
public string Id
{
get { return this.id.Value; }
}
public ClaimSet Issuer
{
get { return ClaimSet.System; }
}
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
for (int i = 0; i < this.claimSets.Count; ++i)
{
evaluationContext.AddClaimSet(this, this.claimSets[i]);
}
if (this.identities != null)
{
object obj;
if (!evaluationContext.Properties.TryGetValue(SecurityUtils.Identities, out obj))
{
evaluationContext.Properties.Add(SecurityUtils.Identities, this.identities);
}
else
{
// null if other overrides the property with something else
List<IIdentity> dstIdentities = obj as List<IIdentity>;
if (dstIdentities != null)
{
dstIdentities.AddRange(this.identities);
}
}
}
evaluationContext.RecordExpirationTime(this.expirationTime);
return true;
}
}
}
}

View File

@@ -0,0 +1,353 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Policy;
using System.IdentityModel.Tokens;
using System.Xml;
public class SecurityContextSecurityToken : SecurityToken, TimeBoundedCache.IExpirableItem, IDisposable
{
byte[] cookieBlob;
UniqueId contextId = null;
UniqueId keyGeneration = null;
DateTime keyEffectiveTime;
DateTime keyExpirationTime;
DateTime tokenEffectiveTime;
DateTime tokenExpirationTime;
bool isCookieMode = false;
byte[] key;
string keyString;
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies;
ReadOnlyCollection<SecurityKey> securityKeys;
string id;
SecurityMessageProperty bootstrapMessageProperty;
bool disposed = false;
public SecurityContextSecurityToken(UniqueId contextId, byte[] key, DateTime validFrom, DateTime validTo)
: this(contextId, SecurityUtils.GenerateId(), key, validFrom, validTo)
{ }
public SecurityContextSecurityToken(UniqueId contextId, string id, byte[] key, DateTime validFrom, DateTime validTo)
: this(contextId, id, key, validFrom, validTo, null)
{ }
public SecurityContextSecurityToken(UniqueId contextId, string id, byte[] key, DateTime validFrom, DateTime validTo, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
: base()
{
this.id = id;
this.Initialize(contextId, key, validFrom, validTo, authorizationPolicies, false, null, validFrom, validTo);
}
public SecurityContextSecurityToken(UniqueId contextId, string id, byte[] key, DateTime validFrom, DateTime validTo, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
: base()
{
this.id = id;
this.Initialize(contextId, key, validFrom, validTo, authorizationPolicies, false, keyGeneration, keyEffectiveTime, keyExpirationTime);
}
internal SecurityContextSecurityToken(SecurityContextSecurityToken sourceToken, string id)
: this(sourceToken, id, sourceToken.key, sourceToken.keyGeneration, sourceToken.keyEffectiveTime, sourceToken.keyExpirationTime, sourceToken.AuthorizationPolicies)
{
}
internal SecurityContextSecurityToken(SecurityContextSecurityToken sourceToken, string id, byte[] key, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
: base()
{
this.id = id;
this.Initialize(sourceToken.contextId, key, sourceToken.ValidFrom, sourceToken.ValidTo, authorizationPolicies, sourceToken.isCookieMode, keyGeneration, keyEffectiveTime, keyExpirationTime);
this.cookieBlob = sourceToken.cookieBlob;
this.bootstrapMessageProperty = (sourceToken.bootstrapMessageProperty == null) ? null : (SecurityMessageProperty)sourceToken.BootstrapMessageProperty.CreateCopy();
}
internal SecurityContextSecurityToken(UniqueId contextId, string id, byte[] key, DateTime validFrom, DateTime validTo, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode, byte[] cookieBlob)
: this(contextId, id, key, validFrom, validTo, authorizationPolicies, isCookieMode, cookieBlob, null, validFrom, validTo)
{
}
internal SecurityContextSecurityToken(UniqueId contextId, string id, byte[] key, DateTime validFrom, DateTime validTo, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode, byte[] cookieBlob,
UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime)
: base()
{
this.id = id;
this.Initialize(contextId, key, validFrom, validTo, authorizationPolicies, isCookieMode, keyGeneration, keyEffectiveTime, keyExpirationTime);
this.cookieBlob = cookieBlob;
}
SecurityContextSecurityToken(SecurityContextSecurityToken from)
{
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = System.IdentityModel.SecurityUtils.CloneAuthorizationPoliciesIfNecessary(from.authorizationPolicies);
this.id = from.id;
this.Initialize(from.contextId, from.key, from.tokenEffectiveTime, from.tokenExpirationTime, authorizationPolicies, from.isCookieMode, from.keyGeneration, from.keyEffectiveTime, from.keyExpirationTime);
this.cookieBlob = from.cookieBlob;
this.bootstrapMessageProperty = (from.bootstrapMessageProperty == null) ? null : (SecurityMessageProperty)from.BootstrapMessageProperty.CreateCopy();
}
/// <summary>
/// Gets or Sets the SecurityMessageProperty extracted from
/// the Bootstrap message. This will contain the original tokens
/// that the client used to Authenticate with the service. By
/// default, this is turned off. To turn this feature on, add a custom
/// ServiceCredentialsSecurityTokenManager and override
/// CreateSecurityTokenManager. Create the SecurityContextToken Authenticator by calling
/// ServiceCredentialsSecurityTokenManager.CreateSecureConversationTokenAuthenticator
/// with 'preserveBootstrapTokens' parameter to true.
/// If there are any UserNameSecurityToken in the bootstrap message, the password in
/// these tokens will be removed. When 'Cookie' mode SCT is enabled the BootstrapMessageProperty
/// is not preserved in the Cookie. To preserve the bootstrap tokens in the CookieMode case
/// write a custom Serializer and serialize the property as part of the cookie.
/// </summary>
public SecurityMessageProperty BootstrapMessageProperty
{
get
{
return this.bootstrapMessageProperty;
}
set
{
this.bootstrapMessageProperty = value;
}
}
public override string Id
{
get { return this.id; }
}
public UniqueId ContextId
{
get
{
return this.contextId;
}
}
public UniqueId KeyGeneration
{
get
{
return this.keyGeneration;
}
}
public DateTime KeyEffectiveTime
{
get
{
return this.keyEffectiveTime;
}
}
public DateTime KeyExpirationTime
{
get
{
return this.keyExpirationTime;
}
}
public ReadOnlyCollection<IAuthorizationPolicy> AuthorizationPolicies
{
get
{
ThrowIfDisposed();
return this.authorizationPolicies;
}
internal set
{
this.authorizationPolicies = value;
}
}
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return this.securityKeys;
}
}
public override DateTime ValidFrom
{
get { return this.tokenEffectiveTime; }
}
public override DateTime ValidTo
{
get { return this.tokenExpirationTime; }
}
internal byte[] CookieBlob
{
get
{
return this.cookieBlob;
}
}
/// <summary>
/// This is set by the issuer when creating the SCT to be sent in the RSTR
/// The SecurityContextTokenManager examines this property to determine how to write
/// out the SCT
/// This field is set to true when the issuer reads in a cookie mode SCT
/// </summary>
public bool IsCookieMode
{
get
{
return this.isCookieMode;
}
}
DateTime TimeBoundedCache.IExpirableItem.ExpirationTime
{
get
{
return this.ValidTo;
}
}
internal string GetBase64KeyString()
{
if (this.keyString == null)
{
this.keyString = Convert.ToBase64String(this.key);
}
return this.keyString;
}
internal byte[] GetKeyBytes()
{
byte[] retval = new byte[this.key.Length];
Buffer.BlockCopy(this.key, 0, retval, 0, this.key.Length);
return retval;
}
public override string ToString()
{
return String.Format(CultureInfo.CurrentCulture, "SecurityContextSecurityToken(Identifier='{0}', KeyGeneration='{1}')", this.contextId, this.keyGeneration);
}
void Initialize(UniqueId contextId, byte[] key, DateTime validFrom, DateTime validTo, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode,
UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime)
{
if (contextId == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextId");
}
if (key == null || key.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
}
DateTime tokenEffectiveTimeUtc = validFrom.ToUniversalTime();
DateTime tokenExpirationTimeUtc = validTo.ToUniversalTime();
if (tokenEffectiveTimeUtc > tokenExpirationTimeUtc)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("validFrom", SR.GetString(SR.EffectiveGreaterThanExpiration));
}
this.tokenEffectiveTime = tokenEffectiveTimeUtc;
this.tokenExpirationTime = tokenExpirationTimeUtc;
this.keyEffectiveTime = keyEffectiveTime.ToUniversalTime();
this.keyExpirationTime = keyExpirationTime.ToUniversalTime();
if (this.keyEffectiveTime > this.keyExpirationTime)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("keyEffectiveTime", SR.GetString(SR.EffectiveGreaterThanExpiration));
}
if ((this.keyEffectiveTime < tokenEffectiveTimeUtc) || (this.keyExpirationTime > tokenExpirationTimeUtc))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.KeyLifetimeNotWithinTokenLifetime));
}
this.key = new byte[key.Length];
Buffer.BlockCopy(key, 0, this.key, 0, key.Length);
this.contextId = contextId;
this.keyGeneration = keyGeneration;
this.authorizationPolicies = authorizationPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
List<SecurityKey> temp = new List<SecurityKey>(1);
temp.Add(new InMemorySymmetricSecurityKey(this.key, false));
this.securityKeys = temp.AsReadOnly();
this.isCookieMode = isCookieMode;
}
public override bool CanCreateKeyIdentifierClause<T>()
{
if (typeof(T) == typeof(SecurityContextKeyIdentifierClause))
return true;
return base.CanCreateKeyIdentifierClause<T>();
}
public override T CreateKeyIdentifierClause<T>()
{
if (typeof(T) == typeof(SecurityContextKeyIdentifierClause))
return new SecurityContextKeyIdentifierClause(this.contextId, this.keyGeneration) as T;
return base.CreateKeyIdentifierClause<T>();
}
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
SecurityContextKeyIdentifierClause sctKeyIdentifierClause = keyIdentifierClause as SecurityContextKeyIdentifierClause;
if (sctKeyIdentifierClause != null)
return sctKeyIdentifierClause.Matches(this.contextId, this.keyGeneration);
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
public static SecurityContextSecurityToken CreateCookieSecurityContextToken(UniqueId contextId, string id, byte[] key,
DateTime validFrom, DateTime validTo, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, SecurityStateEncoder securityStateEncoder)
{
return CreateCookieSecurityContextToken(contextId, id, key, validFrom, validTo, null, validFrom, validTo, authorizationPolicies, securityStateEncoder);
}
public static SecurityContextSecurityToken CreateCookieSecurityContextToken(UniqueId contextId, string id, byte[] key,
DateTime validFrom, DateTime validTo, UniqueId keyGeneration, DateTime keyEffectiveTime,
DateTime keyExpirationTime, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, SecurityStateEncoder securityStateEncoder)
{
SecurityContextCookieSerializer cookieSerializer = new SecurityContextCookieSerializer(securityStateEncoder, null);
byte[] cookieBlob = cookieSerializer.CreateCookieFromSecurityContext(contextId, id, key, validFrom, validTo, keyGeneration,
keyEffectiveTime, keyExpirationTime, authorizationPolicies);
return new SecurityContextSecurityToken(contextId, id, key, validFrom, validTo,
authorizationPolicies, true, cookieBlob, keyGeneration, keyEffectiveTime, keyExpirationTime);
}
internal SecurityContextSecurityToken Clone()
{
ThrowIfDisposed();
return new SecurityContextSecurityToken(this);
}
public void Dispose()
{
if (!this.disposed)
{
this.disposed = true;
System.IdentityModel.SecurityUtils.DisposeAuthorizationPoliciesIfNecessary(this.authorizationPolicies);
if (this.bootstrapMessageProperty != null)
{
this.bootstrapMessageProperty.Dispose();
}
}
}
void ThrowIfDisposed()
{
if (this.disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
}
}

View File

@@ -0,0 +1,48 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security.Tokens
{
using System;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IdentityModel.Policy;
using System.Xml;
public class SecurityContextSecurityTokenAuthenticator : SecurityTokenAuthenticator
{
public SecurityContextSecurityTokenAuthenticator()
: base()
{ }
protected override bool CanValidateTokenCore(SecurityToken token)
{
return (token is SecurityContextSecurityToken);
}
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
{
SecurityContextSecurityToken sct = (SecurityContextSecurityToken)token;
if (!IsTimeValid(sct))
{
this.ThrowExpiredContextFaultException(sct.ContextId, sct);
}
return sct.AuthorizationPolicies;
}
void ThrowExpiredContextFaultException(UniqueId contextId, SecurityContextSecurityToken sct)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityContextTokenValidationException(SR.GetString(SR.SecurityContextExpired, contextId, sct.KeyGeneration == null ? "none" : sct.KeyGeneration.ToString())));
}
bool IsTimeValid(SecurityContextSecurityToken sct)
{
DateTime utcNow = DateTime.UtcNow;
return (sct.ValidFrom <= utcNow && sct.ValidTo >= utcNow && sct.KeyEffectiveTime <= utcNow);
}
}
}

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