/// <summary>
        /// Make sure the issuer matches at least one claim.
        /// Make sure that the claims are provided.
        /// </summary>
        /// <param name="requiredClaims"></param>
        /// <returns></returns>
        bool IClaimsPrincipal.HasRequiredClaims(ClaimSet requiredClaims)
        {
            bool hasClaims   = true;
            bool issuerMatch = false;

            // check at least one claim matches the issuer
            foreach (Claim c in requiredClaims.Issuer)
            {
                if (this.m_claims.Issuer.ContainsClaim(c))
                {
                    issuerMatch = true;
                    break;
                }
            }

            // check all required claims are present
            if (issuerMatch)
            {
                foreach (Claim c in requiredClaims)
                {
                    if (!this.m_claims.ContainsClaim(c))
                    {
                        hasClaims = false;
                        break;
                    }
                }
            }

            return(issuerMatch && hasClaims);
        }
Example #2
0
 public virtual ClaimSet ExtractSubjectKeyClaimSet(SamlSecurityTokenAuthenticator samlAuthenticator)
 {
     if ((this.subjectKeyClaimset == null) && (this.securityKeyIdentifier != null))
     {
         if (samlAuthenticator == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlAuthenticator");
         }
         if (this.subjectToken != null)
         {
             this.subjectKeyClaimset = samlAuthenticator.ResolveClaimSet(this.subjectToken);
             this.identity           = samlAuthenticator.ResolveIdentity(this.subjectToken);
             if ((this.identity == null) && (this.subjectKeyClaimset != null))
             {
                 Claim claim = null;
                 foreach (Claim claim2 in this.subjectKeyClaimset.FindClaims(null, Rights.Identity))
                 {
                     claim = claim2;
                     break;
                 }
                 if (claim != null)
                 {
                     this.identity = System.IdentityModel.SecurityUtils.CreateIdentity(claim.Resource.ToString(), base.GetType().Name);
                 }
             }
         }
         if (this.subjectKeyClaimset == null)
         {
             this.subjectKeyClaimset = samlAuthenticator.ResolveClaimSet(this.securityKeyIdentifier);
             this.identity           = samlAuthenticator.ResolveIdentity(this.securityKeyIdentifier);
         }
     }
     return(this.subjectKeyClaimset);
 }
Example #3
0
        /// <summary>
        /// Has required claims
        /// </summary>
        /// <param name="requiredClaims">Required claim set</param>
        /// <returns><value>True</value> if the issuer has the required claims <value>false</value> if it doesn't</returns>
        public bool HasRequiredClaims(ClaimSet requiredClaims)
        {
            bool hasClaims = true;
           
            // Make sure we have claims to check
            if (this.Claims == null)
            {
                // Token contained no claims, do we need any?
                if (requiredClaims == null || requiredClaims.Count == 0)
                {
                    return true;
                }
                // Deny access
                return false;
            }

            // check issuer
            bool issuerMatch = requiredClaims.Issuer.Any(c => this.Claims.Issuer.ContainsClaim(c));
            
            // check required claims
            if (issuerMatch)
            {
                hasClaims = requiredClaims.All(c => this.Claims.ContainsClaim(c));
            }

            return issuerMatch && hasClaims;
        }
Example #4
0
        bool IClaimSetPrincipal.HasRequiredClaims(ClaimSet requiredClaims)
        {
            // if issuer is null, just check claims from anyone
            // if not, check issuer of claims as well

            return(true);
        }
Example #5
0
        public override IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator)
        {
            if (issuer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");
            }

            // SupportingTokenAuthenticator collection can be null when the Subject does not
            // contain a key.

            if (this.policy == null)
            {
                List <ClaimSet> claimSets          = new List <ClaimSet>();
                ClaimSet        subjectKeyClaimset = this.subject.ExtractSubjectKeyClaimSet(samlAuthenticator);
                if (subjectKeyClaimset != null)
                {
                    claimSets.Add(subjectKeyClaimset);
                }

                List <Claim> claims = new List <Claim>();
                ReadOnlyCollection <Claim> subjectClaims = this.subject.ExtractClaims();
                for (int i = 0; i < subjectClaims.Count; ++i)
                {
                    claims.Add(subjectClaims[i]);
                }

                AddClaimsToList(claims);
                claimSets.Add(new DefaultClaimSet(issuer, claims));
                this.policy = new UnconditionalPolicy(this.subject.Identity, claimSets.AsReadOnly(), SecurityUtils.MaxUtcDateTime);
            }

            return(this.policy);
        }
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="other">The SamlClientCredentials to create a copy of</param>
 protected SamlClientCredentials(SamlClientCredentials other) : base(other)
 {
     // Just do reference copy given sample nature
     this.assertion  = other.assertion;
     this.claims     = other.claims;
     this.proofToken = other.proofToken;
 }
Example #7
0
 /// <summary>
 /// Initializes a new instance of the ClaimsPermission class.
 /// </summary>
 public ClaimsPermission()
 {
     // Initialize the object
     this.isUnrestricted  = true;
     this.isAuthenticated = false;
     this.requiredClaims  = new DefaultClaimSet();
 }
        public void ShouldNotErrorIfClaimSetAlreadyExists()
        {
            var application = SetupContext.Applications.Single(a => a.ApplicationName == "IntegrationTests");

            var claimSet = new ClaimSet
            {
                Application  = application,
                ClaimSetName = "Other ODS AdminApp"
            };

            SetupContext.ClaimSets.Add(claimSet);
            SetupContext.SaveChanges();

            var testClaimSet = new CloudOdsClaimSet
            {
                ApplicationName = "IntegrationTests",
                ClaimSetName    = "Other ODS AdminApp",
                Claims          = new[]
                {
                    new CloudOdsEntityClaim
                    {
                        EntityName            = "educationOrganizations",
                        Actions               = new[] { Create, Read, Update, CloudOdsClaimAction.Delete },
                        AuthorizationStrategy = NoFurtherAuthorizationRequired
                    }
                }
            };

            var configurator = new CloudOdsClaimSetConfigurator(SetupContext);

            configurator.ApplyConfiguration(testClaimSet);
        }
Example #9
0
        internal static string ClaimSetToString(ClaimSet claimSet)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("ClaimSet [");
            for (int i = 0; i < claimSet.Count; i++)
            {
                Claim claim = claimSet[i];
                if (claim != null)
                {
                    sb.Append("  ");
                    sb.AppendLine(claim.ToString());
                }
            }
            string   prefix = "] by ";
            ClaimSet issuer = claimSet;

            do
            {
                issuer = issuer.Issuer;
                sb.AppendFormat("{0}{1}", prefix, issuer == claimSet ? "Self" : (issuer.Count <= 0 ? "Unknown" : issuer[0].ToString()));
                prefix = " -> ";
            } while (issuer.Issuer != issuer);
            return(sb.ToString());
        }
 /// <summary>
 /// Create an object to manage the resources based on a set of claims.
 /// </summary>
 /// <param name="isAuthenticated">Indicates whether the Principal needs to be authenticated.</param>
 /// <param name="requiredClaims">A Set of Claims the Principal must have to use a resource.</param>
 public ClaimsPrincipalPermission(bool isAuthenticated, ClaimSet requiredClaims)
 {
     // Initialize the object
     this.isUnrestricted  = false;
     this.isAuthenticated = isAuthenticated;
     this.requiredClaims  = requiredClaims;
 }
Example #11
0
    private void RetrieveTokenClaims(string xmlToken)
    {
        TokenHelper tokenHelper = new TokenHelper(xmlToken);

        _userClaims = tokenHelper.IdentityClaims;


        foreach (Claim claim in _userClaims)
        {
            switch (claim.ClaimType)
            {
            case "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname":
                _givenName = claim.Resource.ToString();
                break;

            case "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname":
                _surName = claim.Resource.ToString();
                break;

            case "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier":
                _ppid = claim.Resource.ToString();
                break;

            case "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress":
                _email = claim.Resource.ToString();
                break;
            }
        }
    }
        public UnconditionalPolicy(ClaimSet issuance, DateTime expirationTime)
        {
            if (issuance == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuance");

            Initialize(ClaimSet.System, issuance, null, expirationTime);
        }
Example #13
0
        internal static string ClaimSetToString(ClaimSet claimSet)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("ClaimSet [");
            for (int i = 0; i < claimSet.Count; i++)
            {
                Claim claim = claimSet[i];
                if (claim != null)
                {
                    builder.Append("  ");
                    builder.AppendLine(claim.ToString());
                }
            }
            string   str    = "] by ";
            ClaimSet issuer = claimSet;

            do
            {
                issuer = issuer.Issuer;
                builder.AppendFormat("{0}{1}", str, (issuer == claimSet) ? "Self" : ((issuer.Count <= 0) ? "Unknown" : issuer[0].ToString()));
                str = " -> ";
            }while (issuer.Issuer != issuer);
            return(builder.ToString());
        }
Example #14
0
        private void Initialize(ClaimSet issuer, ClaimSet issuance, ReadOnlyCollection <ClaimSet> issuances, DateTime expirationTime)
        {
            _issuer         = issuer;
            _issuance       = issuance;
            _issuances      = issuances;
            _expirationTime = expirationTime;

            // We don't yet support WindowsClaimSet
            //if (issuance != null)
            //{
            //    _disposable = issuance is WindowsClaimSet;
            //}
            //else
            //{
            //    for (int i = 0; i < issuances.Count; ++i)
            //    {
            //        if (issuances[i] is WindowsClaimSet)
            //        {
            //            this.disposable = true;
            //            break;
            //        }
            //    }
            //}

            _disposable = false;
        }
Example #15
0
        private static void ShowClaimSetHtml(ClaimSet set, bool isIssuer, bool verbose)
        {
            if (set.HasIssuer())
            {
                ShowClaimSetHtml(set.Issuer, true, verbose);
            }

            string setType = set.GetType().Name;
            string setName = isIssuer ? "Issuer" : "Issued";

            HeadingHtml(String.Format("\n{0} Claims ({1})\n", setName, setType));

            foreach (Claim claim in set)
            {
                bool isIdentity = claim.Right.Equals(Rights.Identity);

                WriteLineHtml(claim.ClaimType, isIdentity);

                if (verbose)
                {
                    WriteLineHtml(claim.Resource.GetType().FullName, isIdentity);
                    WriteLineHtml(claim.Stringify(), isIdentity);
                }
                else
                {
                    WriteLineHtml(claim.Resource.ToString(), isIdentity);
                }

                WriteLineHtml(claim.Right, isIdentity);
                WriteLineHtml("", false);

                Console.ResetColor();
            }
        }
Example #16
0
 internal static void DisposeClaimSetIfNecessary(ClaimSet claimSet)
 {
     if (claimSet != null)
     {
         DisposeIfNecessary(claimSet as WindowsClaimSet);
     }
 }
Example #17
0
        string ISecureService.SendMessage(string message)
        {
            AuthorizationContext authContext = ServiceSecurityContext.Current.AuthorizationContext;

            DateTime?birthDate = null;

            foreach (ClaimSet cs in authContext.ClaimSets)
            {
                // check for self-issued claims
                ClaimSet csIssuer = cs.Issuer;
                if (csIssuer == csIssuer.Issuer)
                {
                    IEnumerable <Claim> claims = cs.FindClaims(ClaimTypes.DateOfBirth, Rights.PossessProperty);
                    foreach (Claim c in claims)
                    {
                        birthDate = Convert.ToDateTime(c.Resource);
                    }
                }
            }

            if (birthDate == null)
            {
                throw new SecurityException("Missing date of birth claim.");
            }
            if (birthDate.Value.AddYears(13) > DateTime.Now)
            {
                throw new SecurityException("User is too young to access this operation.");
            }

            string s = String.Format("Message '{0}' received. \r\n\r\nHost identity is {1}\r\n Security context PrimaryIdentity is {2}\r\n Security context WindowsIdentity is {3}\r\n Thread identity is {4}", message, WindowsIdentity.GetCurrent().Name, ServiceSecurityContext.Current.PrimaryIdentity.Name, ServiceSecurityContext.Current.WindowsIdentity.Name, Thread.CurrentPrincipal.Identity.Name);

            return(s);
        }
        /// <summary>
        /// Serializes a claim set using the DataContractSerializer.
        /// </summary>
        /// <param name="set">the claim set to serialize</param>
        /// <param name="knownTypes">known serialization types</param>
        /// <returns></returns>
        public static XElement Serialize(this ClaimSet set, IEnumerable <Type> knownTypes)
        {
            // make sure lazy loading has been done before serialization
            var dlset = set as DeferredLoadClaimSet;

            if (dlset != null)
            {
                dlset.Load();
            }

            DataContractSerializer dcs = new DataContractSerializer(
                set.GetType(),
                knownTypes,
                int.MaxValue,
                false,
                true,
                null);

            MemoryStream ms = new MemoryStream();

            dcs.WriteObject(ms, set);
            ms.Seek(0, SeekOrigin.Begin);

            return(XElement.Load(new XmlTextReader(ms)));
        }
Example #19
0
        bool IClaimSetPrincipal.HasRequiredClaims(ClaimSet requiredClaims)
        {
            // if issuer is null, just check claims from anyone
            // if not, check issuer of claims as well

            return true;
        }
        public override IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator)
        {
            if (issuer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");

            // SupportingTokenAuthenticator collection can be null when the Subject does not
            // contain a key.

            if (this.policy == null)
            {
                List<ClaimSet> claimSets = new List<ClaimSet>();
                ClaimSet subjectKeyClaimset = this.subject.ExtractSubjectKeyClaimSet(samlAuthenticator);
                if (subjectKeyClaimset != null)
                    claimSets.Add(subjectKeyClaimset);

                List<Claim> claims = new List<Claim>();
                ReadOnlyCollection<Claim> subjectClaims = this.subject.ExtractClaims();
                for (int i = 0; i < subjectClaims.Count; ++i)
                {
                    claims.Add(subjectClaims[i]);
                }

                AddClaimsToList(claims);
                claimSets.Add(new DefaultClaimSet(issuer, claims));
                this.policy = new UnconditionalPolicy(this.subject.Identity, claimSets.AsReadOnly(), SecurityUtils.MaxUtcDateTime);
            }

            return this.policy;
        }
 protected PeerSecurityTraceRecord(string meshId, string remoteAddress, ClaimSet claimSet, Exception exception)
 {
     this.meshId        = meshId;
     this.remoteAddress = remoteAddress;
     this.claimSet      = claimSet;
     this.exception     = exception;
 }
Example #22
0
        private static SamlAssertion CreateAssertion(ClaimSet claims, SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, SecurityAlgorithmSuite algoSuite)
        {
            SamlSubject samlSubject = new SamlSubject(null, null, "Self", new List <string>(1)
            {
                SamlConstants.HolderOfKey
            }, null, proofKeyIdentifier);
            IList <SamlAttribute> list = new List <SamlAttribute>();

            foreach (Claim claim in claims)
            {
                if (typeof(string) == claim.Resource.GetType())
                {
                    list.Add(new SamlAttribute(claim));
                }
            }
            SamlAttributeStatement item  = new SamlAttributeStatement(samlSubject, list);
            List <SamlStatement>   list2 = new List <SamlStatement>();

            list2.Add(item);
            SigningCredentials signingCredentials = new SigningCredentials(signatureKey, algoSuite.DefaultAsymmetricSignatureAlgorithm, algoSuite.DefaultDigestAlgorithm, signatureKeyIdentifier);
            DateTime           utcNow             = DateTime.UtcNow;

            return(new SamlAssertion("_" + Guid.NewGuid().ToString(), "Self", utcNow, new SamlConditions(utcNow, utcNow + new TimeSpan(10, 0, 0)), new SamlAdvice(), list2)
            {
                SigningCredentials = signingCredentials
            });
        }
 protected PeerSecurityTraceRecord(string meshId, string remoteAddress, ClaimSet claimSet, Exception exception)
 {
     this.meshId = meshId;
     this.remoteAddress = remoteAddress;
     this.claimSet = claimSet;
     this.exception = exception;
 }
Example #24
0
        internal static string ClaimSetToString(ClaimSet claimSet)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("ClaimSet [");
            for (int i = 0; i < claimSet.Count; i++)
            {
                Claim claim = claimSet[i];
                if (claim != null)
                {
                    sb.Append("  ");
                    sb.AppendLine(claim.ToString());
                }
            }
            string   prefix = "] by ";
            ClaimSet issuer = claimSet;

            do
            {
                // PreSharp Bug: A null-dereference can occur here.
#pragma warning suppress 56506 // issuer was just set to this.
                issuer = issuer.Issuer;
                sb.AppendFormat("{0}{1}", prefix, issuer == claimSet ? "Self" : (issuer.Count <= 0 ? "Unknown" : issuer[0].ToString()));
                prefix = " -> ";
            } while (issuer.Issuer != issuer);
            return(sb.ToString());
        }
 public override IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator)
 {
     if (issuer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");
     }
     if (this.policy == null)
     {
         List<ClaimSet> list = new List<ClaimSet>();
         ClaimSet item = this.subject.ExtractSubjectKeyClaimSet(samlAuthenticator);
         if (item != null)
         {
             list.Add(item);
         }
         List<Claim> claims = new List<Claim>();
         ReadOnlyCollection<Claim> onlys = this.subject.ExtractClaims();
         for (int i = 0; i < onlys.Count; i++)
         {
             claims.Add(onlys[i]);
         }
         this.AddClaimsToList(claims);
         list.Add(new DefaultClaimSet(issuer, claims));
         this.policy = new UnconditionalPolicy(this.subject.Identity, list.AsReadOnly(), System.IdentityModel.SecurityUtils.MaxUtcDateTime);
     }
     return this.policy;
 }
        /// <summary>
        /// Evaluate the set of incoming claims.
        /// </summary>
        /// <param name="evaluationContext">The results of the authorization policies that have been evaluated.</param>
        /// <param name="state">The current state of the authorization evaluation.</param>
        /// <returns>true indicates evaluation of the authorization can continue, false will reject the authorization.</returns>
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            // A new principal with its associated claims is created for the first identity to have been evaluated by the transport
            // layer.  This principal will be applied to the thread before the operations are called.
            object property = null;

            if (evaluationContext.Properties.TryGetValue("Identities", out property))
            {
                List <IIdentity> identities = property as List <IIdentity>;
                if (identities != null)
                {
                    foreach (IIdentity iIdentity in identities)
                    {
                        ///HACK - we are only interested custom username
                        if (iIdentity.AuthenticationType != "Kerberos")
                        {
                            ClaimSet        claimSet        = MapClaims(iIdentity);
                            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(iIdentity, claimSet);
                            evaluationContext.Properties["Principal"] = claimsPrincipal;
                            evaluationContext.AddClaimSet(this, claimSet);
                        }
                    }
                }
            }
            else
            {
                // If there was no identity provided by the transport, then a generic identity with no claims is used.  This user
                // will only be able to access 'Unrestricted' methods of an interface.
                ClaimSet emptyClaims = new DefaultClaimSet(ClaimsAuthorizationPolicy.IssuerClaimSet, new Claim[] { });
                evaluationContext.Properties["Principal"] = new ClaimsPrincipal(new GenericIdentity("Default User"), emptyClaims);
            }

            // There is no need to call the evaluation again, everything here is computed in a single pass.
            return(true);
        }
		Task<IAccessToken> INonCachingAccessTokenProvider.ProvisionAccessTokenAsync(
			ClaimSet claimSet,	
			IEnumerable<Scope> scopes
		) {
			var @this = this as INonCachingAccessTokenProvider;
			return @this.ProvisionAccessTokenAsync( claimSet.ToClaims(), scopes );
		}
Example #28
0
        string ICrudService.UpdateSomething()
        {
            AuthorizationContext authContext = ServiceSecurityContext.Current.AuthorizationContext;

            ClaimSet issuerClaimSet = null;

            foreach (ClaimSet cs in authContext.ClaimSets)
            {
                Claim issuerClaim = Claim.CreateNameClaim("http://www.thatindigogirl.com/samples/2006/06/issuer");

                if (cs.Issuer.ContainsClaim(issuerClaim))
                {
                    issuerClaimSet = cs;
                }
            }

            if (issuerClaimSet == null)
            {
                throw new SecurityException("Access is denied. No claims were provided from the expected issuer.");
            }

            Claim c = new Claim("http://schemas.thatindigogirl.com/samples/2006/06/identity/claims/update", "http://schemas.thatindigogirl.com/samples/2006/06/identity/resources/application", Rights.PossessProperty);

            if (!issuerClaimSet.ContainsClaim(c))
            {
                throw new SecurityException("Access is denied. Required claims not satisfied.");
            }

            return(String.Format("UpdateSomething() called by user {0}", System.Threading.Thread.CurrentPrincipal.Identity.Name));
        }
Example #29
0
        public void InitiateHandShake()
        {
            IPeerNeighbor neighbor = host;
            Message       reply    = null;

            Fx.Assert(host != null, "Cannot initiate security handshake without a host!");

            //send the RST message.
            using (OperationContextScope scope = new OperationContextScope(new OperationContext((ServiceHostBase)null)))
            {
                PeerHashToken token   = this.securityManager.GetSelfToken();
                Message       request = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, TrustFeb2005Strings.RequestSecurityToken, new PeerRequestSecurityToken(token));
                bool          fatal   = false;
                try
                {
                    reply = neighbor.RequestSecurityToken(request);

                    if (!(reply != null))
                    {
                        throw Fx.AssertAndThrow("SecurityHandshake return empty message!");
                    }
                    ProcessRstr(neighbor, reply, PeerSecurityManager.FindClaim(ServiceSecurityContext.Current));
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        fatal = true;
                        throw;
                    }
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    this.state = PeerAuthState.Failed;
                    if (DiagnosticUtility.ShouldTraceError)
                    {
                        ServiceSecurityContext context = ServiceSecurityContext.Current;
                        ClaimSet claimSet = null;
                        if (context != null && context.AuthorizationContext != null && context.AuthorizationContext.ClaimSets != null && context.AuthorizationContext.ClaimSets.Count > 0)
                        {
                            claimSet = context.AuthorizationContext.ClaimSets[0];
                        }
                        PeerAuthenticationFailureTraceRecord record = new PeerAuthenticationFailureTraceRecord(
                            meshId,
                            neighbor.ListenAddress.EndpointAddress.ToString(),
                            claimSet,
                            e);
                        TraceUtility.TraceEvent(TraceEventType.Error,
                                                TraceCode.PeerNodeAuthenticationFailure, SR.GetString(SR.TraceCodePeerNodeAuthenticationFailure),
                                                record, this, null);
                    }
                    neighbor.Abort(PeerCloseReason.AuthenticationFailure, PeerCloseInitiator.LocalNode);
                }
                finally
                {
                    if (!fatal)
                    {
                        request.Close();
                    }
                }
            }
        }
Example #30
0
        /// <summary>
        /// Creates a SAML assertion based on an Asymmetric proof key
        /// </summary>
        /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param>
        /// <param name="proofToken">An  RsaSecurityToken containing the proof key</param>
        /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param>
        /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the proof key</returns>
        public static SamlAssertion CreateAsymmetricKeyBasedAssertion(ClaimSet claims, SecurityToken proofToken, SecurityAlgorithmSuite algoSuite)
        {
            // Check various input parameters
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            if (proofToken == null)
            {
                throw new ArgumentNullException("proofToken");
            }

            if (claims.Count == 0)
            {
                throw new ArgumentException("Provided ClaimSet must contain at least one claim");
            }

            // Create key identifier for proof key
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(proofToken.CreateKeyIdentifierClause <RsaKeyIdentifierClause>());
            // Get signing key and a key identifier for same
            SecurityKey           signatureKey           = proofToken.SecurityKeys[0];
            SecurityKeyIdentifier signatureKeyIdentifier = proofKeyIdentifier;

            // Create the assertion
            return(CreateAssertion(claims, signatureKey, signatureKeyIdentifier, proofKeyIdentifier, algoSuite));
        }
Example #31
0
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            // get claims from authorized issuer
            ClaimSet issuedClaims = null;

            foreach (ClaimSet cs in evaluationContext.ClaimSets)
            {
                // If the issuer of the ClaimSet is this STS...
                if (cs.Issuer.ContainsClaim(Claim.CreateDnsClaim("IPKey")))
                {
                    issuedClaims = cs;
                }
            }

            if (issuedClaims == null)
            {
                throw new SecurityException("Unable to authenticate caller. Invalid claimset provided.");
            }

            CustomIdentity  identity     = new CustomIdentity("Claims");
            CustomPrincipal newPrincipal = new CustomPrincipal(identity, issuedClaims);

            evaluationContext.Properties["Principal"] = newPrincipal;

            return(true);
        }
        [Ignore("not up to date")]          // X509Chain
        public void DefaultValues()
        {
            X509Chain chain = new X509Chain();

            chain.Build(cert);
            Assert.IsTrue(chain.ChainElements.Count > 1, "#0");
            ClaimSet cs    = new X509CertificateClaimSet(cert);
            ClaimSet ident = cs.Issuer;
            X509CertificateClaimSet x509is = ident as X509CertificateClaimSet;

            Assert.IsNotNull(x509is, "#0-2");
            Assert.AreEqual(chain.ChainElements [1].Certificate, x509is.X509Certificate, "#0-3");
            Assert.AreEqual(6, cs.Count, "#1");
            Assert.AreEqual(6, ident.Issuer.Count, "#2");
            Assert.IsFalse(cs.ContainsClaim(Claim.System), "#3");
            List <string> d = new List <string> ();

            foreach (Claim c in cs)
            {
                if (c.ClaimType != ClaimTypes.Thumbprint)
                {
                    Assert.AreEqual(Rights.PossessProperty, c.Right, "#4");
                }
                d.Add(c.ClaimType);
            }
            Assert.IsTrue(d.Contains(ClaimTypes.X500DistinguishedName), "#5");
            Assert.IsTrue(d.Contains(ClaimTypes.Thumbprint), "#6");
            Assert.IsTrue(d.Contains(ClaimTypes.Dns), "#7");
            Assert.IsTrue(d.Contains(ClaimTypes.Rsa), "#8");
            Assert.IsTrue(d.Contains(ClaimTypes.Name), "#9");
        }
Example #33
0
        private void Initialize(ClaimSet issuer, ClaimSet issuance, ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime)
        {
            _issuer = issuer;
            _issuance = issuance;
            _issuances = issuances;
            _expirationTime = expirationTime;

            // We don't yet support WindowsClaimSet
            //if (issuance != null)
            //{
            //    _disposable = issuance is WindowsClaimSet;
            //}
            //else
            //{
            //    for (int i = 0; i < issuances.Count; ++i)
            //    {
            //        if (issuances[i] is WindowsClaimSet)
            //        {
            //            this.disposable = true;
            //            break;
            //        }
            //    }
            //}

            _disposable = false;
        }
 public override IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator)
 {
     if (issuer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");
     }
     if (this.policy == null)
     {
         List <ClaimSet> list = new List <ClaimSet>();
         ClaimSet        item = this.subject.ExtractSubjectKeyClaimSet(samlAuthenticator);
         if (item != null)
         {
             list.Add(item);
         }
         List <Claim> claims = new List <Claim>();
         ReadOnlyCollection <Claim> onlys = this.subject.ExtractClaims();
         for (int i = 0; i < onlys.Count; i++)
         {
             claims.Add(onlys[i]);
         }
         this.AddClaimsToList(claims);
         list.Add(new DefaultClaimSet(issuer, claims));
         this.policy = new UnconditionalPolicy(this.subject.Identity, list.AsReadOnly(), System.IdentityModel.SecurityUtils.MaxUtcDateTime);
     }
     return(this.policy);
 }
Example #35
0
 /// <summary>
 /// Copy constructor
 /// </summary>
 /// <param name="other">The SamlClientCredentials to create a copy of</param>
 protected SamlClientCredentials(SamlClientCredentials other) : base ( other )
 {
     // Just do reference copy given sample nature
     this.assertion = other.assertion;            
     this.claims = other.claims;
     this.proofToken = other.proofToken;            
 }
 public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
 {
     if (identity == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
     }
     if (authContext == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
     }
     for (int i = 0; i < authContext.ClaimSets.Count; i++)
     {
         ClaimSet claimSet = authContext.ClaimSets[i];
         if (claimSet.ContainsClaim(identity.IdentityClaim))
         {
             SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(identity, identity.IdentityClaim, base.GetType());
             return(true);
         }
         string expectedSpn = null;
         if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
         {
             expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", new object[] { (string)identity.IdentityClaim.Resource });
             Claim claim = this.CheckDnsEquivalence(claimSet, expectedSpn);
             if (claim != null)
             {
                 SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(identity, claim, base.GetType());
                 return(true);
             }
         }
         SecurityIdentifier identitySid = null;
         if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = this.GetSecurityIdentifier(identity.IdentityClaim);
         }
         else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = ((UpnEndpointIdentity)identity).GetUpnSid();
         }
         else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = ((SpnEndpointIdentity)identity).GetSpnSid();
         }
         else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = new SpnEndpointIdentity(expectedSpn).GetSpnSid();
         }
         if (identitySid != null)
         {
             Claim claim2 = this.CheckSidEquivalence(identitySid, claimSet);
             if (claim2 != null)
             {
                 SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(identity, claim2, base.GetType());
                 return(true);
             }
         }
     }
     SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, base.GetType());
     return(false);
 }
Example #37
0
 internal static ClaimSet CloneClaimSetIfNecessary(ClaimSet claimSet)
 {
     if (claimSet != null)
     {
         throw ExceptionHelper.PlatformNotSupported();
     }
     return(claimSet);
 }
		async Task<IAccessToken> IAccessTokenProvider.ProvisionAccessTokenAsync(
			ClaimSet claimSet,
			IEnumerable<Scope> scopes,
			ICache cache
    ) {
			var @this = this as IAccessTokenProvider;
			return await @this.ProvisionAccessTokenAsync( claimSet.ToClaims(), scopes, cache ).SafeAsync();
		}
 public CreditCardTokenAuthorizationPolicy(ClaimSet issuedClaims)
 {
     if (issuedClaims == null)
         throw new ArgumentNullException("issuedClaims");
     this.issuer = issuedClaims.Issuer;
     this.issuedClaimSets = new ClaimSet[] { issuedClaims };
     this.id = Guid.NewGuid().ToString();
 }
 /// <summary>
 /// Utility function to create an EndpointIdentity from a ClaimSet
 /// </summary>
 /// <param name="claims">Claims to create the EndpointIdentity with</param>
 /// <returns>An EndpointIdentity</returns>
 private EndpointIdentity CreateIdentityFromClaimSet(ClaimSet claims)
 {
     foreach (Claim claim in claims.FindClaims(null, Rights.Identity))
     {
         return(EndpointIdentity.CreateIdentity(claim));
     }
     return(null);
 }
 public UnconditionalPolicy(ClaimSet issuance, DateTime expirationTime)
 {
     if (issuance == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuance");
     }
     this.Initialize(ClaimSet.System, issuance, null, expirationTime);
 }
        internal SecurityTokenAuthorizationPolicy( ClaimSet issuedClaims )
        {
            if ( issuedClaims == null )
                throw new ArgumentNullException( "issuedClaims" );

            _issuer = issuedClaims.Issuer;
            _issuedClaimSets = new[] { issuedClaims };
            _id = Guid.NewGuid().ToString();
        }
        public CustomAuthorizationPolicy()
        {
            m_id = Guid.NewGuid();

            Claim c = Claim.CreateNameClaim("http://www.thatindigogirl.com/samples/2006/07/issuer");
            Claim[] claims = new Claim[1];
            claims[0] = c;
            m_issuer = new DefaultClaimSet(claims);
        }
Example #44
0
 bool TryGetStringClaimValue(ClaimSet claimSet, string claimType, out string claimValue)
 {
     claimValue = null;
     IEnumerable<Claim> matchingClaims = claimSet.FindClaims(claimType, Rights.PossessProperty);
     if (matchingClaims == null)
         return false;
     IEnumerator<Claim> enumerator = matchingClaims.GetEnumerator();
     enumerator.MoveNext();
     claimValue = (enumerator.Current.Resource == null) ? null : enumerator.Current.Resource.ToString();
     return true;
 }
        public override void AddClaimSet(IAuthorizationPolicy policy, ClaimSet claimSet)
        {
            if (claimSet == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claimSet");

            if (_claimSets == null)
                _claimSets = new List<ClaimSet>();

            _claimSets.Add(claimSet);
            ++_generation;
        }
        public UnconditionalPolicy(ClaimSet issuer, ClaimSet issuance, DateTime expirationTime, IList<IIdentity> identities)
        {
            if (issuer == null)
                throw new ArgumentNullException("issuer");
            if (issuance == null)
                throw new ArgumentNullException("issuance");

            this.issuer = issuer;
            this.issuance = issuance;
            this.identities = identities;
            this.expirationTime = expirationTime;
        }
 protected void Initialize(ClaimSet issuer, IList<Claim> claims)
 {
     if (issuer == null)
     {
         throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");
     }
     if (claims == null)
     {
         throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claims");
     }
     this.issuer = issuer;
     this.claims = claims;
 }
 public override void AddClaimSet(IAuthorizationPolicy policy, ClaimSet claimSet)
 {
     if (claimSet == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claimSet");
     }
     if (this.claimSets == null)
     {
         this.claimSets = new List<ClaimSet>();
     }
     this.claimSets.Add(claimSet);
     this.generation++;
 }
        protected override void LoadClaims(out ClaimSet issuer, out IList<Claim> claims)
        {
            issuer = _issuer;

            claims = new List<Claim>()
            {
                CreateCustomerClaimId(),
                CreateCustomerClaimProp(),
                CreatePurchaseLimitClaim(),
                CreateLastActivityClaim(),
                CreateStatusClaim(),
            };
        }
 UnconditionalPolicy(UnconditionalPolicy from)
 {
     this.disposable = from.disposable;
     this.primaryIdentity = from.disposable ? SecurityUtils.CloneIdentityIfNecessary(from.primaryIdentity) : from.primaryIdentity;
     if (from.issuance != null)
     {
         this.issuance = from.disposable ? SecurityUtils.CloneClaimSetIfNecessary(from.issuance) : from.issuance;
     }
     else
     {
         this.issuances = from.disposable ? SecurityUtils.CloneClaimSetsIfNecessary(from.issuances) : from.issuances;
     }
     this.issuer = from.issuer;
     this.expirationTime = from.expirationTime;
 }
 private UnconditionalPolicy(UnconditionalPolicy from)
 {
     _disposable = from._disposable;
     _primaryIdentity = from._disposable ? SecurityUtils.CloneIdentityIfNecessary(from._primaryIdentity) : from._primaryIdentity;
     if (from._issuance != null)
     {
         _issuance = from._disposable ? SecurityUtils.CloneClaimSetIfNecessary(from._issuance) : from._issuance;
     }
     else
     {
         _issuances = from._disposable ? SecurityUtils.CloneClaimSetsIfNecessary(from._issuances) : from._issuances;
     }
     _issuer = from._issuer;
     _expirationTime = from._expirationTime;
 }
		public async Task ProvisionAccessTokenAsync_LegacyClaimSetOverload_DoesRightThing() {
			var claimSet = new ClaimSet(
				issuer: TestData.ISSUER,
				tenantId: TestData.TENANT_ID,
				user: TestData.USER
			);

			await m_accessTokenProvider
				.ProvisionAccessTokenAsync( claimSet, new Scope[] { } )
				.SafeAsync();

			AssertClaimEquals( m_actualAssertion, Constants.Claims.ISSUER, TestData.ISSUER );
			AssertClaimEquals( m_actualAssertion, Constants.Claims.TENANT_ID, TestData.TENANT_ID.ToString() );
			AssertClaimEquals( m_actualAssertion, Constants.Claims.USER_ID, TestData.USER );
		}
        private static void ShowClaimSet(ClaimSet set, bool isIssuer, bool verbose)
        {
            if (set.HasIssuer())
            {
                ShowClaimSet(set.Issuer, true, verbose);
            }

            string setType = set.GetType().Name;
            string setName = isIssuer ? "Issuer" : "Issued";

            Heading(String.Format("\n{0} Claims ({1})\n", setName, setType),
                ConsoleColor.Green);

            if (set.Count == 0)
            {
                Console.WriteLine("(anonymous)\n");
            }

            foreach (Claim claim in set)
            {
                if (claim.Right.Equals(Rights.Identity))
                {
                    Console.ForegroundColor = ConsoleColor.White;
                }

                Console.WriteLine(claim.ClaimType);

                if (verbose)
                {
                    Console.WriteLine(claim.Resource.GetType().FullName);
                    Console.WriteLine(claim.Stringify());
                }
                else
                {
                    Console.WriteLine(claim.Resource);
                }

                Console.WriteLine(claim.Right);
                Console.WriteLine();

                Console.ResetColor();
            }
        }
Example #54
0
        /// <summary>
        /// Creates a SAML assertion based on a symmetric proof key
        /// </summary>
        /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param>
        /// <param name="signatureToken">An X509SecurityToken that will be used to sign the SAML assertion</param>
        /// <param name="encryptionToken">An X509SecurityToken that will be used to encrypt the proof key</param>
        /// <param name="proofToken">A BinarySecretSecurityToken containing the proof key</param>
        /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param>
        /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the provided signature token</returns>
        public static SamlAssertion CreateSymmetricKeyBasedAssertion(ClaimSet claims, X509SecurityToken signatureToken, X509SecurityToken encryptionToken, BinarySecretSecurityToken proofToken, SecurityAlgorithmSuite algoSuite)
        {
            // Check various input parameters
            if (claims == null)
                throw new ArgumentNullException("claims");

            if (claims.Count == 0)
                throw new ArgumentException("Provided ClaimSet must contain at least one claim");

            if (proofToken == null)
                throw new ArgumentNullException("proofToken");

            if (signatureToken == null)
                throw new ArgumentNullException("signatureToken");

            if (encryptionToken == null)
                throw new ArgumentNullException("encryptionToken");

            if (proofToken == null)
                throw new ArgumentNullException("proofToken");

            if (algoSuite == null)
                throw new ArgumentNullException("algoSuite");

            // Get signing key and a key identifier for same
            SecurityKey signatureKey = signatureToken.SecurityKeys[0];
            SecurityKeyIdentifierClause signatureSkic = signatureToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier signatureKeyIdentifier  = new SecurityKeyIdentifier(signatureSkic);

            // Get encryption key and a key identifier for same
            SecurityKey encryptionKey = encryptionToken.SecurityKeys[0];
            SecurityKeyIdentifierClause encryptionSkic = encryptionToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier encryptionKeyIdentifier = new SecurityKeyIdentifier(encryptionSkic);

            // Encrypt the proof key and create a key identifier for same
            byte[] proofKey = proofToken.GetKeyBytes();
            byte[] encryptedSecret = new byte[proofKey.Length];
            encryptedSecret = encryptionKey.EncryptKey(algoSuite.DefaultAsymmetricKeyWrapAlgorithm, proofKey);
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(new EncryptedKeyIdentifierClause(encryptedSecret, algoSuite.DefaultAsymmetricKeyWrapAlgorithm, encryptionKeyIdentifier));

            // Create the assertion
            return CreateAssertion(claims, signatureKey, signatureKeyIdentifier, proofKeyIdentifier, algoSuite);
        }
Example #55
0
        /// <summary>
        /// Creates a SAML assertion based on an Asymmetric proof key
        /// </summary>
        /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param>
        /// <param name="proofToken">An  RsaSecurityToken containing the proof key</param>
        /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param>
        /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the proof key</returns>
        public static SamlAssertion CreateAsymmetricKeyBasedAssertion(ClaimSet claims, SecurityToken proofToken, SecurityAlgorithmSuite algoSuite)
        {
            // Check various input parameters
            if (claims == null)
                throw new ArgumentNullException("claims");

            if (proofToken == null)
                throw new ArgumentNullException("proofToken");

            if (claims.Count == 0)
                throw new ArgumentException("Provided ClaimSet must contain at least one claim");

            // Create key identifier for proof key
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(proofToken.CreateKeyIdentifierClause<RsaKeyIdentifierClause>());
            // Get signing key and a key identifier for same
            SecurityKey signatureKey = proofToken.SecurityKeys[0];
            SecurityKeyIdentifier signatureKeyIdentifier = proofKeyIdentifier;

            // Create the assertion
            return CreateAssertion(claims, signatureKey, signatureKeyIdentifier, proofKeyIdentifier, algoSuite);
        }
 void Initialize(ClaimSet issuer, ClaimSet issuance, ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime)
 {
     this.issuer = issuer;
     this.issuance = issuance;
     this.issuances = issuances;
     this.expirationTime = expirationTime;
     if (issuance != null)
     {
         this.disposable = issuance is WindowsClaimSet;
     }
     else
     {
         for (int i = 0; i < issuances.Count; ++i)
         {
             if (issuances[i] is WindowsClaimSet)
             {
                 this.disposable = true;
                 break;
             }
         }
     }
 }
 internal static void WriteClaimSet(XmlWriter writer, ClaimSet claimSet)
 {
     writer.WriteStartElement("NeighborCredentials");
     if (claimSet != null)
     {
         foreach (Claim claim in claimSet)
         {
             if (claim.ClaimType == ClaimTypes.Name)
             {
                 writer.WriteElementString("Name", claim.Resource.ToString());
             }
             else if (claim.ClaimType == ClaimTypes.X500DistinguishedName)
             {
                 writer.WriteElementString("X500DistinguishedName", (claim.Resource as X500DistinguishedName).Name.ToString());
             }
             else if (claim.ClaimType == ClaimTypes.Thumbprint)
             {
                 writer.WriteElementString("Thumbprint", Convert.ToBase64String(claim.Resource as byte[]));
             }
         }
     }
     writer.WriteEndElement();
 }
 internal static string ClaimSetToString(ClaimSet claimSet)
 {
     StringBuilder builder = new StringBuilder();
     builder.AppendLine("ClaimSet [");
     for (int i = 0; i < claimSet.Count; i++)
     {
         Claim claim = claimSet[i];
         if (claim != null)
         {
             builder.Append("  ");
             builder.AppendLine(claim.ToString());
         }
     }
     string str = "] by ";
     ClaimSet issuer = claimSet;
     do
     {
         issuer = issuer.Issuer;
         builder.AppendFormat("{0}{1}", str, (issuer == claimSet) ? "Self" : ((issuer.Count <= 0) ? "Unknown" : issuer[0].ToString()));
         str = " -> ";
     }
     while (issuer.Issuer != issuer);
     return builder.ToString();
 }
 public abstract IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator);
Example #60
0
 internal Claim CheckDnsEquivalence(ClaimSet claimSet, string expectedSpn)
 {
     // host/<machine-name> satisfies the DNS identity claim
     IEnumerable<Claim> claims = claimSet.FindClaims(ClaimTypes.Spn, Rights.PossessProperty);
     foreach (Claim claim in claims)
     {
         if (expectedSpn.Equals((string)claim.Resource, StringComparison.OrdinalIgnoreCase))
         {
             return claim;
         }
     }
     return null;
 }