Exemple #1
0
			public override bool CheckAccess (
				EndpointIdentity identity,
				AuthorizationContext authContext)
			{
				// FIXME: implement
				throw new NotImplementedException ();
			}
        static IList<Type> BuildKnownClaimTypes(AuthorizationContext authorizationContext)
        {
            List<Type> knownTypes = new List<Type>();

            foreach (ClaimSet claimSet in authorizationContext.ClaimSets)
            {
                Type claimSetType = claimSet.GetType();

                if (!redBitsKnownType.Contains(claimSetType) && !knownTypes.Contains(claimSetType))
                {
                    knownTypes.Add(claimSetType);
                }

                foreach (Claim claim in claimSet)
                {
                    Type claimType = claim.GetType();

                    if (!redBitsKnownType.Contains(claimType) && !knownTypes.Contains(claimType))
                    {
                        knownTypes.Add(claimType);
                    }
                }
            }

            if (knownTypes.Count != 0)
            {
                return knownTypes;
            }

            return null;
        }
 public ServiceSecurityContext(ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies)
 {
     if (authorizationPolicies == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
     }
     this.authorizationContext  = null;
     this.authorizationPolicies = authorizationPolicies;
 }
 // Perf: delay created authorizationContext using forward chain.
 public ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
 {
     if (authorizationPolicies == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
     }
     _authorizationContext = null;
     _authorizationPolicies = authorizationPolicies;
 }
        private static IList<IIdentity> GetIdentities(AuthorizationContext authorizationContext)
        {
            object list;
            if ((authorizationContext != null) && authorizationContext.Properties.TryGetValue("Identities", out list))
            {
                return (list as IList<IIdentity>);
            }

            return new List<IIdentity>();
        }
        /// <summary>
        /// The the purposes of this method are:
        /// 1. To enable layers above to get to the bootstrap tokens
        /// 2. To ensure an ClaimsPrincipal is inside the SCT authorization policies.  This is needed so that
        ///    a CustomPrincipal will be created and can be set.  This is required as we set the principal permission mode to custom
        /// 3. To set the IAuthorizationPolicy collection on the SCT to be one of IDFx's Authpolicy.
        /// This allows SCT cookie and SCT cached to be treated the same, futher up the stack.
        ///
        /// This method is call AFTER the final SCT has been created and the bootstrap tokens are around.  Itis not called during the SP/TLS nego bootstrap.
        /// </summary>
        /// <param name="sct"></param>
        internal void SetPrincipalBootstrapTokensAndBindIdfxAuthPolicy(SecurityContextSecurityToken sct)
        {
            if (sct == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sct");
            }

            List <IAuthorizationPolicy> iaps = new List <IAuthorizationPolicy>();

            //
            // The SecurityContextToken is cached first before the OnTokenIssued is called. So in the Session SCT
            // case the AuthorizationPolicies will have already been updated. So check the sct.AuthorizationPolicies
            // policy to see if the first is a AuthorizationPolicy.
            //
            if ((sct.AuthorizationPolicies != null) &&
                (sct.AuthorizationPolicies.Count > 0) &&
                (ContainsEndpointAuthPolicy(sct.AuthorizationPolicies)))
            {
                // We have already seen this sct and have fixed up the AuthorizationPolicy
                // collection. Just return.
                return;
            }

            //
            // Nego SCT just has a cookie, there are no IAuthorizationPolicy. In this case,
            // we want to add the EndpointAuthorizationPolicy alone to the SCT.
            //
            if ((sct.AuthorizationPolicies != null) &&
                (sct.AuthorizationPolicies.Count > 0))
            {
                //
                // Create a principal with known policies.
                //
                AuthorizationPolicy sctAp = IdentityModelServiceAuthorizationManager.TransformAuthorizationPolicies(sct.AuthorizationPolicies,
                                                                                                                    _securityTokenHandlerCollection,
                                                                                                                    false);
                // Replace the WCF authorization policies with our IDFx policies.
                // The principal is needed later on to set the custom principal by WCF runtime.
                iaps.Add(sctAp);

                //
                // Convert the claim from WCF unconditional policy to an SctAuthorizationPolicy. The SctAuthorizationPolicy simply
                // captures the primary identity claim from the WCF unconditional policy which IdFX will eventually throw away.
                // If we don't capture that claim, then in a token renewal scenario WCF will fail due to identities being different
                // for the issuedToken and the renewedToken.
                //
                SysClaim claim = GetPrimaryIdentityClaim(SystemAuthorizationContext.CreateDefaultAuthorizationContext(sct.AuthorizationPolicies));

                SctAuthorizationPolicy sctAuthPolicy = new SctAuthorizationPolicy(claim);
                iaps.Add(sctAuthPolicy);
            }

            iaps.Add(new EndpointAuthorizationPolicy(_endpointId));
            sct.AuthorizationPolicies = iaps.AsReadOnly();
        }
        private IList <IIdentity> GetIdentities()
        {
            object obj2;

            System.IdentityModel.Policy.AuthorizationContext authorizationContext = this.AuthorizationContext;
            if ((authorizationContext != null) && authorizationContext.Properties.TryGetValue("Identities", out obj2))
            {
                return(obj2 as IList <IIdentity>);
            }
            return(null);
        }
        public static SerializableAuthorizationContext From(AuthorizationContext authorizationContext)
        {
            if (authorizationContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
            }

            IList<Type> knownTypes = BuildKnownClaimTypes(authorizationContext);
            byte[] contextBlob = CreateSerializableBlob(authorizationContext, knownTypes);

            return new SerializableAuthorizationContext(contextBlob, authorizationContext.ExpirationTime, authorizationContext.Id, knownTypes);
        }
 public ServiceSecurityContext(System.IdentityModel.Policy.AuthorizationContext authorizationContext, ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies)
 {
     if (authorizationContext == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
     }
     if (authorizationPolicies == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
     }
     this.authorizationContext  = authorizationContext;
     this.authorizationPolicies = authorizationPolicies;
 }
 public ServiceSecurityContext(System.IdentityModel.Policy.AuthorizationContext authorizationContext, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
 {
     if (authorizationContext == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
     }
     if (authorizationPolicies == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
     }
     this.authorizationContext = authorizationContext;
     this.authorizationPolicies = authorizationPolicies;
 }
		public ServiceSecurityContext (AuthorizationContext authorizationContext,
			ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
		{
			if (authorizationContext == null)
				throw new ArgumentNullException ("authorizationContext");
			if (authorizationPolicies == null)
				throw new ArgumentNullException ("authorizationPolicies");
			this.policies = authorizationPolicies;
			this.context = authorizationContext;

			// FIXME: get correct identity
			primary_identity = new GenericIdentity (String.Empty);
		}
		public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authzContext) {
			List<Claim> dnsClaims = new List<Claim>();
			foreach( ClaimSet claimSet in authzContext.ClaimSets ) {
				foreach( Claim claim in claimSet ) {
					if ( ClaimTypes.Dns == claim.ClaimType ) {
						dnsClaims.Add(claim);
					}
				}
			}
			if ( 1 != dnsClaims.Count ) {
				throw new InvalidOperationException(String.Format("Found {0} DNS claims in authorization context.", dnsClaims.Count));
			}
			return String.Equals((string) this.expectedIdentity.IdentityClaim.Resource, (string) dnsClaims[0].Resource, StringComparison.OrdinalIgnoreCase);
		}
Exemple #13
0
 /// <summary>
 /// Gets the primary identity claim to create the SCTAuthorizationPolicy
 /// </summary>
 /// <param name="authContext">The authorization context</param>
 /// <returns>The primary identity claim from the authorization context.</returns>
 SysClaim GetPrimaryIdentityClaim(SystemAuthorizationContext authContext)
 {
     if (authContext != null)
     {
         for (int i = 0; i < authContext.ClaimSets.Count; ++i)
         {
             System.IdentityModel.Claims.ClaimSet claimSet = authContext.ClaimSets[i];
             foreach (System.IdentityModel.Claims.Claim claim in claimSet.FindClaims(null, System.IdentityModel.Claims.Rights.Identity))
             {
                 return(claim);
             }
         }
     }
     return(null);
 }
 private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference)
 {
     if (((identity.IdentityClaim == null) || !(identity.IdentityClaim.ClaimType == ClaimTypes.Dns)) || (!(identity.IdentityClaim.Right == Rights.PossessProperty) || !(identity.IdentityClaim.Resource is string)))
     {
         return new MessageSecurityException(System.ServiceModel.SR.GetString(errorString, new object[] { identity, serviceReference }));
     }
     string resource = (string) identity.IdentityClaim.Resource;
     string str2 = null;
     for (int i = 0; i < authorizationContext.ClaimSets.Count; i++)
     {
         ClaimSet set = authorizationContext.ClaimSets[i];
         foreach (Claim claim in set.FindClaims(ClaimTypes.Dns, Rights.PossessProperty))
         {
             if (claim.Resource is string)
             {
                 str2 = (string) claim.Resource;
                 break;
             }
         }
         if (str2 != null)
         {
             break;
         }
     }
     if ("IdentityCheckFailedForIncomingMessage".Equals(errorString))
     {
         if (str2 == null)
         {
             return new MessageSecurityException(System.ServiceModel.SR.GetString("DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim", new object[] { resource }));
         }
         return new MessageSecurityException(System.ServiceModel.SR.GetString("DnsIdentityCheckFailedForIncomingMessage", new object[] { resource, str2 }));
     }
     if ("IdentityCheckFailedForOutgoingMessage".Equals(errorString))
     {
         if (str2 == null)
         {
             return new MessageSecurityException(System.ServiceModel.SR.GetString("DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim", new object[] { resource }));
         }
         return new MessageSecurityException(System.ServiceModel.SR.GetString("DnsIdentityCheckFailedForOutgoingMessage", new object[] { resource, str2 }));
     }
     return new MessageSecurityException(System.ServiceModel.SR.GetString(errorString, new object[] { identity, serviceReference }));
 }
 private bool AccessCheck(AuthorizationContext authzContext, MessageProperties messageProperties, string claimType, Dictionary<Claim, Claim> dictionary)
 {
     if (authzContext != null)
     {
         foreach (ClaimSet set in authzContext.ClaimSets)
         {
             foreach (Claim claim in set.FindClaims(claimType, Rights.PossessProperty))
             {
                 if (dictionary.ContainsKey(claim))
                 {
                     return true;
                 }
             }
         }
     }
     else if (DebugTrace.Info)
     {
         DebugTrace.Trace(TraceLevel.Info, "No authzContext was passed into AccessCheck");
     }
     return false;
 }
        // Code to be added.
        public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
        {
            StreamWriter file = new StreamWriter("c:\\temp\\TestClient.CustomIdentityVerifier - CheckAccess.txt", true);
            file.WriteLine("_________________________________________");
            file.WriteLine("DateTime: " + DateTime.Now.ToString());

            bool returnvalue = false;

            foreach (ClaimSet claimset in authContext.ClaimSets)
            {
                foreach (Claim claim in claimset)
                {
                    file.WriteLine("claim.ClaimType: " + claim.ClaimType);
                    file.WriteLine("\tclaim.Right: " + claim.Right);
                    file.WriteLine("\t\tclaim.Resource: " + claim.Resource.ToString());

                    if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname")
                    {
                        X500DistinguishedName name = (X500DistinguishedName)claim.Resource;
                        file.WriteLine("X500DistinguishedName: " + name.Name);

                        //if (name.Name.Contains(((OrgEndpointIdentity)identity).OrganizationClaim))
                        //if ("CN=zpatlittrs239.ittl.gtri.org" == name.Name)
                        if ("[email protected], CN=HA50WSP, O=Hawaii Five0, L=Honolulu, S=Hawaii, C=US" == name.Name)
                        {
                            file.WriteLine("\tClaim Type: {0}", claim.ClaimType);
                            file.WriteLine("\tRight: {0}", claim.Right);
                            file.WriteLine("\tResource: {0}", claim.Resource);
                            file.WriteLine();
                            returnvalue = true;
                        }
                    }
                }

            }

            file.Close();

            return returnvalue;
        }
Exemple #17
0
 private void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString)
 {
     if (authorizationContext == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
     }
     EndpointIdentity identity;
     if (!TryGetIdentity(serviceReference, out identity))
     {
         SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, this.GetType());
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(errorString, identity, serviceReference)));
     }
     else
     {
         if (!CheckAccess(identity, authorizationContext))
         {
             // CheckAccess performs a Trace on failure, no need to do it twice
             Exception e = CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference);
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(e);
         }
     }
 }
 private bool AccessCheck(AuthorizationContext authzContext, MessageProperties messageProperties, string binding)
 {
     bool result = false;
     if (DebugTrace.Verbose)
     {
         DebugTrace.Trace(TraceLevel.Verbose, "AccessCheck for binding {0}", binding);
     }
     if (string.Compare(binding, BindingStrings.InteropBindingQName(this.protocolVersion), StringComparison.Ordinal) == 0)
     {
         result = this.AccessCheck(authzContext, messageProperties, ClaimTypes.Thumbprint, this.thumbprints);
     }
     else if ((string.Compare(binding, BindingStrings.NamedPipeBindingQName, StringComparison.Ordinal) == 0) || (string.Compare(binding, BindingStrings.WindowsBindingQName, StringComparison.Ordinal) == 0))
     {
         result = this.AccessCheck(authzContext, messageProperties, ClaimTypes.Sid, this.sids);
     }
     else
     {
         Microsoft.Transactions.Bridge.DiagnosticUtility.FailFast("Unknown binding " + binding);
     }
     this.TraceAccessCheckResult(result, messageProperties);
     return result;
 }
Exemple #19
0
        /// <summary>
        /// Token Constructor
        /// </summary>
        /// <param name="xmlToken">Encrypted xml token</param>
        public Token(String xmlToken)
        {
            byte[] decryptedData = decryptToken(xmlToken);

            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8));
            m_token = (SamlSecurityToken)WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null);

            SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                                            new SecurityTokenAuthenticator[]{
                                                                new RsaSecurityTokenAuthenticator(),
                                                                new X509SecurityTokenAuthenticator() }), MaximumTokenSkew);

            if (authenticator.CanValidateToken(m_token))
            {
                ReadOnlyCollection<IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token);
                m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies);
                FindIdentityClaims();
            }
            else
            {
                throw new Exception("Unable to validate the token.");
            }
        }
Exemple #20
0
 public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext);
Exemple #21
0
 internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, Uri via, AuthorizationContext authorizationContext)
 {
     AdjustAddress(ref serviceReference, via);
     this.EnsureIdentity(serviceReference, authorizationContext, SR.IdentityCheckFailedForOutgoingMessage);
 }
Exemple #22
0
        public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
        {
            bool returnvalue = false;

            foreach (ClaimSet claimset in authContext.ClaimSets)
            {
                foreach (Claim claim in claimset)
                {
                    if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname")
                    {
                        X500DistinguishedName name = (X500DistinguishedName)claim.Resource;
                        if (name.Name.Contains(((OrgEndpointIdentity)identity).OrganizationClaim))
                        {
                            Console.WriteLine("Claim Type: {0}", claim.ClaimType);
                            Console.WriteLine("Right: {0}", claim.Right);
                            Console.WriteLine("Resource: {0}", claim.Resource);
                            Console.WriteLine();
                            returnvalue = true;
                        }
                    }
                }

            }
            return returnvalue;
        }
Exemple #23
0
            public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
            {
                EventTraceActivity eventTraceActivity = null;
 
                if (identity == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
 
                if (authContext == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
 
 
                if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
                {
                    eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
                }
 
                for (int i = 0; i < authContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authContext.ClaimSets[i];
                    if (claimSet.ContainsClaim(identity.IdentityClaim))
                    {
                        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType());
                        return true;
                    }
 
                    // try Claim equivalence
                    string expectedSpn = null;
                    if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    {
                        expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
                        Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
                        if (claim != null)
                        {
                            SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                            return true;
                        }
                    }

                    // Allow a Sid claim to support UPN, and SPN identities
                    
                    // SID claims not available yet 
                    //SecurityIdentifier identitySid = null;
                    //if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid");
                    //}
                    //else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn");
                    //}
                    //else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn");
                    //}
                    //else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns");
                    //}
                    //if (identitySid != null)
                    //{
                    //    Claim claim = CheckSidEquivalence(identitySid, claimSet);
                    //    if (claim != null)
                    //    {
                    //        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                    //        return true;
                    //    }
                    //}
                }
                SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType());
                if (WcfEventSource.Instance.SecurityIdentityVerificationFailureIsEnabled())
                {
                    WcfEventSource.Instance.SecurityIdentityVerificationFailure(eventTraceActivity);
                }

                return false; 
            }
		/// <summary>
		/// Generates a UniqueID based off the Issuer's key and the PPID.
		/// </summary>
		/// <param name="authzContext">The Authorization Context</param>
		/// <returns>A unique ID for this user at this web site.</returns>
		internal static string GetUniqueName(AuthorizationContext authzContext) {
			Requires.NotNull(authzContext, "authzContext");

			Claim uniqueIssuerClaim = null;
			Claim uniqueUserClaim = null;

			foreach (ClaimSet cs in authzContext.ClaimSets) {
				Claim currentIssuerClaim = GetUniqueRsaClaim(cs.Issuer);

				foreach (Claim c in cs.FindClaims(ClaimTypes.PPID, Rights.PossessProperty)) {
					if (null == currentIssuerClaim) {
						// Found a claim in a ClaimSet with no RSA issuer.
						return null;
					}

					if (null == uniqueUserClaim) {
						uniqueUserClaim = c;
						uniqueIssuerClaim = currentIssuerClaim;
					} else if (!uniqueIssuerClaim.Equals(currentIssuerClaim)) {
						// Found two of the desired claims with different
						// issuers. No unique name.
						return null;
					} else if (!uniqueUserClaim.Equals(c)) {
						// Found two of the desired claims with different
						// values. No unique name.
						return null;
					}
				}
			}

			// No claim of the desired type was found
			if (null == uniqueUserClaim) {
				return null;
			}

			// Unexpected resource type
			string claimValue = uniqueUserClaim.Resource as string;
			if (null == claimValue) {
				return null;
			}

			// Unexpected resource type for RSA
			RSA rsa = uniqueIssuerClaim.Resource as RSA;
			if (null == rsa) {
				return null;
			}

			return ComputeCombinedId(rsa, claimValue);
		}
 internal void EnsureIncomingIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext)
 {
     EnsureIdentity(serviceReference, authorizationContext, SR.IdentityCheckFailedForIncomingMessage);
 }
 internal static void TraceIdentityVerificationFailure(EndpointIdentity identity, AuthorizationContext authContext, Type identityVerifier)
 {
 }
 public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
 {
     return true;
 }
 public static void SerializeIdentities(AuthorizationContext authContext, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer)
 {
     object obj2;
     if (authContext.Properties.TryGetValue("Identities", out obj2))
     {
         IList<IIdentity> list = obj2 as IList<IIdentity>;
         if ((list != null) && (list.Count > 0))
         {
             writer.WriteStartElement(dictionary.Identities, dictionary.EmptyString);
             for (int i = 0; i < list.Count; i++)
             {
                 SerializePrimaryIdentity(list[i], dictionary, writer, serializer);
             }
             writer.WriteEndElement();
         }
     }
 }
 public ServiceSecurityContext(AuthorizationContext authorizationContext)
     : this(authorizationContext, EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance)
 {
 }
        private void ParseToken(string xmlToken, X509Certificate2 cert)
        {
            int skew = 300; // default to 5 minutes
            string tokenskew = System.Configuration.ConfigurationManager.AppSettings["MaximumClockSkew"];
            if (!string.IsNullOrEmpty(tokenskew))
                skew = Int32.Parse(tokenskew);

            XmlReader tokenReader = new XmlTextReader(new StringReader(xmlToken));
            EncryptedData enc = new EncryptedData();

            enc.TokenSerializer = WSSecurityTokenSerializer.DefaultInstance;

            enc.ReadFrom(tokenReader);

            List<SecurityToken> tokens = new List<SecurityToken>();
            SecurityToken encryptingToken = new X509SecurityToken(cert);
            tokens.Add(encryptingToken);

            SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
            SymmetricSecurityKey encryptingCrypto;

            // an error here usually means that you have selected the wrong key.
            encryptingCrypto = (SymmetricSecurityKey)tokenResolver.ResolveSecurityKey(enc.KeyIdentifier[0]);

            SymmetricAlgorithm algorithm = encryptingCrypto.GetSymmetricAlgorithm(enc.EncryptionMethod);

            byte[] decryptedData = enc.GetDecryptedBuffer(algorithm);

            SecurityTokenSerializer tokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8));

            m_token = (SamlSecurityToken)tokenSerializer.ReadToken(reader, tokenResolver);

            SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                                            new SecurityTokenAuthenticator[]{
                                                                new RsaSecurityTokenAuthenticator(),
                                                                new X509SecurityTokenAuthenticator() }), new TimeSpan(0, 0, skew));

            if (authenticator.CanValidateToken(m_token))
            {
                ReadOnlyCollection<IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token);
                m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies);
                m_identityClaims = FindIdentityClaims(m_authorizationContext);
            }
            else
            {
                throw new Exception("Unable to validate the token.");
            }
        }
        public ClaimSet FindIdentityClaims(AuthorizationContext authContext)
        {
            // Pick up the claim type to use for generating the UniqueID claim
            string identificationClaimType = System.Configuration.ConfigurationManager.AppSettings["IdentityClaimType"];

            // Or, default to PPID
            if (string.IsNullOrEmpty(identificationClaimType))
                identificationClaimType = System.IdentityModel.Claims.ClaimTypes.PPID;

            ClaimSet result = null;
            m_endpointIdentity = null;

            foreach (ClaimSet claimSet in authContext.ClaimSets)
            {
                //
                // This loops through the claims looking for the configured claim type
                // that will be used as part of the generation of the unique id.
                //
                foreach (Claim claim in claimSet.FindClaims(identificationClaimType, Rights.PossessProperty))
                {
                    // found a matching claim. This is good.
                    EndpointIdentity issuerId = CreateIdentityFromClaimSet(claimSet.Issuer);
                    byte[] issuerkey;

                    // we need to get a byte array that represents the issuer's key
                    // to use as part of the hash to generate a unique id.
                    // currently supported: (byte[]) or an RSACryptoServiceProvider,
                    // This could be expanded to support other types. The key just
                    // needs to be extracted as a byte array.
                    issuerkey = issuerId.IdentityClaim.Resource as byte[];
                    if (null == issuerkey)
                    {
                        RSACryptoServiceProvider csp = issuerId.IdentityClaim.Resource as RSACryptoServiceProvider;
                        if (null != csp)
                            issuerkey = csp.ExportCspBlob(false);

                        // Can't use this claim to get the key.
                        if (null == issuerkey)
                            throw new Exception("Unsupported IdentityClaim resource type");
                    }

                    // It doesn't matter what encoding type we use, as long as it is consistent.
                    // this conversion is just to get a consistent set of bytes from the claim.
                    byte[] uniqueClaim = Encoding.UTF8.GetBytes(GetResourceValue(claim));

                    // copy the thumbprint data and the uniqueClaim together.
                    byte[] thumbprintData = new byte[uniqueClaim.Length + issuerkey.Length];
                    issuerkey.CopyTo(thumbprintData, 0);
                    uniqueClaim.CopyTo(thumbprintData, issuerkey.Length);

                    // generate a hash.
                    using (SHA256 sha = new SHA256Managed())
                    {
                        Claim thumbprintClaim = new Claim(ClaimTypes.Thumbprint, Convert.ToBase64String(sha.ComputeHash(thumbprintData)), Rights.Identity);
                        m_endpointIdentity = EndpointIdentity.CreateIdentity(thumbprintClaim);
                    }

                    return claimSet;
                }

                if (null == m_endpointIdentity)
                {
                    //
                    // check for identity claim, if found, hold on to it, we may need to use it :)
                    //
                    result = claimSet;
                    m_endpointIdentity = CreateIdentityFromClaimSet(claimSet);
                }
            }

            if (null != m_endpointIdentity)
            {
                return result;
            }

            //
            // we have looped all claim sets with out finding an identity claim.
            // we will return the ppidIdentity and claimset if they were found.
            //
            throw new Exception("The XML Token data provided no Identity claim.");
        }
		public ServiceSecurityContext (AuthorizationContext authorizationContext)
			: this (authorizationContext, new ReadOnlyCollection<IAuthorizationPolicy> (new IAuthorizationPolicy [0]))
		{
		}
 public ServiceSecurityContext(System.IdentityModel.Policy.AuthorizationContext authorizationContext) : this(authorizationContext, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance)
 {
 }
		/// <summary>
		/// Generates a UniqueID based off the Issuer's key
		/// </summary>
		/// <param name="authzContext">the Authorization Context</param>
		/// <returns>the hash of the internal key of the issuer</returns>
		internal static string GetIssuerPubKeyHash(AuthorizationContext authzContext) {
			foreach (ClaimSet cs in authzContext.ClaimSets) {
				Claim currentIssuerClaim = GetUniqueRsaClaim(cs.Issuer);

				if (currentIssuerClaim != null) {
					RSA rsa = currentIssuerClaim.Resource as RSA;
					if (null == rsa) {
						return null;
					}

					return ComputeCombinedId(rsa, string.Empty);
				}
			}

			return null;
		}
Exemple #35
0
        private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference)
        {
            Exception result;
 
            if (identity.IdentityClaim != null
                && identity.IdentityClaim.ClaimType == ClaimTypes.Dns
                && identity.IdentityClaim.Right == Rights.PossessProperty
                && identity.IdentityClaim.Resource is string)
            {
                string expectedDnsName = (string)identity.IdentityClaim.Resource;
                string actualDnsName = null;
                for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authorizationContext.ClaimSets[i];
                    foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty))
                    {
                        if (claim.Resource is string)
                        {
                            actualDnsName = (string)claim.Resource;
                            break;
                        }
                    }
                    if (actualDnsName != null)
                    {
                        break;
                    }
                }
                if (SR.IdentityCheckFailedForIncomingMessage.Equals(errorString))
                {
                    if (actualDnsName == null)
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName));
                    }
                    else
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName));
                    }
                }
                else if (SR.IdentityCheckFailedForOutgoingMessage.Equals(errorString))
                {
                    if (actualDnsName == null)
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName));
                    }
                    else
                    {
                        result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName));
                    }
                }
                else
                {
                    result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
                }
            }
            else
            {
                result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
            }
 
            return result;
        }
Exemple #36
0
        /// <summary>
        /// Converts a given set of WCF IAuthorizationPolicy to WIF ClaimIdentities.
        /// </summary>
        /// <param name="authorizationPolicies">Set of AuthorizationPolicies to convert to IDFx.</param>
        /// <param name="securityTokenHandlerCollection">The SecurityTokenHandlerCollection to use.</param>
        /// <returns>ClaimsIdentityCollection</returns>
        static ReadOnlyCollection <ClaimsIdentity> ConvertToIDFxIdentities(IList <IAuthorizationPolicy> authorizationPolicies,
                                                                           SecurityTokenHandlerCollection securityTokenHandlerCollection)
        {
            if (authorizationPolicies == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
            }

            if (securityTokenHandlerCollection == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenHandlerCollection");
            }

            List <ClaimsIdentity> identities = new List <ClaimsIdentity>();

            SecurityTokenSpecification kerberosTokenSpecification = null;
            SysAuthorizationContext    kerberosAuthContext        = null;

            if ((OperationContext.Current != null) &&
                (OperationContext.Current.IncomingMessageProperties != null) &&
                (OperationContext.Current.IncomingMessageProperties.Security != null))
            {
                SecurityMessageProperty securityMessageProperty = OperationContext.Current.IncomingMessageProperties.Security;
                foreach (SecurityTokenSpecification tokenSpecification in new SecurityTokenSpecificationEnumerable(securityMessageProperty))
                {
                    if (tokenSpecification.SecurityToken is KerberosReceiverSecurityToken)
                    {
                        kerberosTokenSpecification = tokenSpecification;
                        kerberosAuthContext        = SysAuthorizationContext.CreateDefaultAuthorizationContext(kerberosTokenSpecification.SecurityTokenPolicies);
                        break;
                    }
                }
            }

            bool hasKerberosTokenPolicyMatched = false;

            foreach (IAuthorizationPolicy policy in authorizationPolicies)
            {
                bool authPolicyHandled = false;

                if ((kerberosTokenSpecification != null) && !hasKerberosTokenPolicyMatched)
                {
                    if (kerberosTokenSpecification.SecurityTokenPolicies.Contains(policy))
                    {
                        hasKerberosTokenPolicyMatched = true;
                    }
                    else
                    {
                        SysAuthorizationContext authContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List <IAuthorizationPolicy>()
                        {
                            policy
                        });
                        // Kerberos creates only one ClaimSet. So any more ClaimSet would mean that this is not a Policy created from Kerberos.
                        if (authContext.ClaimSets.Count == 1)
                        {
                            bool allClaimsMatched = true;
                            foreach (System.IdentityModel.Claims.Claim c in authContext.ClaimSets[0])
                            {
                                if (!kerberosAuthContext.ClaimSets[0].ContainsClaim(c))
                                {
                                    allClaimsMatched = false;
                                    break;
                                }
                            }
                            hasKerberosTokenPolicyMatched = allClaimsMatched;
                        }
                    }

                    if (hasKerberosTokenPolicyMatched)
                    {
                        SecurityTokenHandler tokenHandler = securityTokenHandlerCollection[kerberosTokenSpecification.SecurityToken];
                        if ((tokenHandler != null) && tokenHandler.CanValidateToken)
                        {
                            identities.AddRange(tokenHandler.ValidateToken(kerberosTokenSpecification.SecurityToken));
                            authPolicyHandled = true;
                        }
                    }
                }

                if (!authPolicyHandled)
                {
                    SysAuthorizationContext defaultAuthContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List <IAuthorizationPolicy>()
                    {
                        policy
                    });
                    //
                    // Merge all ClaimSets to IClaimsIdentity.
                    //

                    identities.Add(ConvertToIDFxIdentity(defaultAuthContext.ClaimSets, securityTokenHandlerCollection.Configuration));
                }
            }

            return(identities.AsReadOnly());
        }
 public static void SerializeIdentities(AuthorizationContext authContext, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer)
 {
     object obj;
     IList<IIdentity> identities;
     if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj))
     {
         identities = obj as IList<IIdentity>;
         if (identities != null && identities.Count > 0)
         {
             writer.WriteStartElement(dictionary.Identities, dictionary.EmptyString);
             for (int i = 0; i < identities.Count; ++i)
             {
                 SerializePrimaryIdentity(identities[i], dictionary, writer, serializer);
             }
             writer.WriteEndElement();
         }
     }
 }
Exemple #38
0
        /// <summary>
        /// Returns true if the IAuthorizationPolicy could have been created from the given Transport token.
        /// The method can handle only X509SecurityToken and WindowsSecurityToken.
        /// </summary>
        /// <param name="transportToken">Client's Security Token provided at the transport layer.</param>
        /// <param name="tranportTokenIdentities">A collection of <see cref="ClaimsIdentity"/> to match.</param>
        /// <param name="authPolicy">IAuthorizationPolicy to check.</param>
        /// <returns>True if the IAuthorizationPolicy could have been created from the given Transpor token.</returns>
        static bool DoesPolicyMatchTransportToken(
            SecurityToken transportToken,
            IEnumerable <ClaimsIdentity> tranportTokenIdentities,
            IAuthorizationPolicy authPolicy
            )
        {
            if (transportToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("transportToken");
            }

            if (tranportTokenIdentities == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tranportTokenIdentities");
            }

            if (authPolicy == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authPolicy");
            }

            //////////////////////////////////////////////////////////////////////////////////////////
            //
            // There are 5 Client Authentication types at the transport layer. Each of these will
            // result either in a WindowsSecurityToken, X509SecurityToken or UserNameSecurityToken.
            //
            //      ClientCredential Type     ||        Transport Token Type
            // -------------------------------------------------------------------
            //          Basic                 ->        UserNameSecurityToken (In Self-hosted case)
            //          Basic                 ->        WindowsSecurityToken (In Web-Hosted case)
            //          NTLM                  ->        WindowsSecurityToken
            //          Negotiate             ->        WindowsSecurityToken
            //          Windows               ->        WindowsSecurityToken
            //          Certificate           ->        X509SecurityToken
            //
            //////////////////////////////////////////////////////////////////////////////////////////
            X509SecurityToken x509SecurityToken = transportToken as X509SecurityToken;

            SysAuthorizationContext defaultAuthContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List <IAuthorizationPolicy>()
            {
                authPolicy
            });

            foreach (System.IdentityModel.Claims.ClaimSet claimset in defaultAuthContext.ClaimSets)
            {
                if (x509SecurityToken != null)
                {
                    // Check if the claimset contains a claim that matches the X.509 certificate thumbprint.
                    if (claimset.ContainsClaim(new System.IdentityModel.Claims.Claim(
                                                   System.IdentityModel.Claims.ClaimTypes.Thumbprint,
                                                   x509SecurityToken.Certificate.GetCertHash(),
                                                   System.IdentityModel.Claims.Rights.PossessProperty)))
                    {
                        return(true);
                    }
                }
                else
                {
                    // For WindowsSecurityToken and UserNameSecurityToken check that IClaimsdentity.Name
                    // matches the Name Claim in the ClaimSet.
                    // In most cases, we will have only one Identity in the ClaimsIdentityCollection
                    // generated from transport token.
                    foreach (ClaimsIdentity transportTokenIdentity in tranportTokenIdentities)
                    {
                        if (claimset.ContainsClaim(new System.IdentityModel.Claims.Claim(
                                                       System.IdentityModel.Claims.ClaimTypes.Name,
                                                       transportTokenIdentity.Name,
                                                       System.IdentityModel.Claims.Rights.PossessProperty), new ClaimStringValueComparer()))
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }