public static SecurityContextSecurityToken CreateCookieSecurityContextToken(
            UniqueId contextId,
            string id,
            byte [] key,
            DateTime validFrom,
            DateTime validTo,
            UniqueId keyGeneration,
            DateTime keyEffectiveTime,
            DateTime keyExpirationTime,
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies,
            SecurityStateEncoder securityStateEncoder)
        {
            if (securityStateEncoder == null)
            {
                throw new ArgumentNullException("securityStateEncoder");
            }

            SecurityContextSecurityToken sct = new SecurityContextSecurityToken(
                contextId, id, key, validFrom, validTo,
                keyGeneration, keyEffectiveTime,
                keyExpirationTime, authorizationPolicies);

            byte [] rawdata = SslnegoCookieResolver.CreateData(
                contextId, keyGeneration, key,
                validFrom, validTo,
                keyEffectiveTime, keyExpirationTime);
            sct.cookie = securityStateEncoder.EncodeSecurityState(rawdata);
            return(sct);
        }
 public void AddContext(SecurityContextSecurityToken token)
 {
     if (!TryAddContext(token))
     {
         throw new InvalidOperationException("Argument token is already in the cache.");
     }
 }
Exemple #3
0
        public SecurityContextSecurityToken CreateSecurityContextFromCookie(byte[] encodedCookie, UniqueId contextId, UniqueId generation, string id, XmlDictionaryReaderQuotas quotas)
        {
            byte[] serializedContext = null;
            try
            {
                serializedContext = this.securityStateEncoder.DecodeSecurityState(encodedCookie);
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                OnInvalidCookieFailure(System.ServiceModel.SR.GetString("SctCookieBlobDecodeFailure"), exception);
            }
            SecurityContextSecurityToken token = this.DeserializeContext(serializedContext, encodedCookie, id, quotas);

            if (token.ContextId != contextId)
            {
                OnInvalidCookieFailure(System.ServiceModel.SR.GetString("SctCookieValueMissingOrIncorrect", new object[] { "ContextId" }));
            }
            if (token.KeyGeneration != generation)
            {
                OnInvalidCookieFailure(System.ServiceModel.SR.GetString("SctCookieValueMissingOrIncorrect", new object[] { "KeyGeneration" }));
            }
            return(token);
        }
Exemple #4
0
 internal SecurityContextSecurityToken(SecurityContextSecurityToken sourceToken, string id, byte[] key, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime, ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies)
 {
     this.id = id;
     this.Initialize(sourceToken.contextId, key, sourceToken.ValidFrom, sourceToken.ValidTo, authorizationPolicies, sourceToken.isCookieMode, keyGeneration, keyEffectiveTime, keyExpirationTime);
     this.cookieBlob = sourceToken.cookieBlob;
     this.bootstrapMessageProperty = (sourceToken.bootstrapMessageProperty == null) ? null : ((SecurityMessageProperty)sourceToken.BootstrapMessageProperty.CreateCopy());
 }
Exemple #5
0
        protected override SecurityKeyIdentifierClause CreateKeyIdentifierClause(
            SecurityToken token, SecurityTokenReferenceStyle referenceStyle)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            SecurityContextSecurityToken sct = token as SecurityContextSecurityToken;

            if (sct == null)
            {
                throw new ArgumentException(String.Format("Not supported SecurityToken: '{0}'", token));
            }
            return(referenceStyle == SecurityTokenReferenceStyle.Internal ?
                   (SecurityKeyIdentifierClause)
                   new LocalIdKeyIdentifierClause(sct.Id) :
                   new SecurityContextKeyIdentifierClause(sct.ContextId, sct.KeyGeneration));

            /*
             * GenericXmlSecurityToken x = token as GenericXmlSecurityToken;
             * if (x == null)
             *      throw new ArgumentException (String.Format ("Not supported SecurityToken: '{0}'", token));
             * return referenceStyle == SecurityTokenReferenceStyle.Internal ? x.InternalTokenReference : x.ExternalTokenReference;
             */
        }
        public static void CreateIssuedToken(Guid transactionId, string coordinationContextId, ProtocolVersion protocolVersion, out RequestSecurityTokenResponse issuedToken, out string sctId)
        {
            sctId = CoordinationContext.CreateNativeIdentifier(Guid.NewGuid());
            byte[] key = DeriveIssuedTokenKey(transactionId, sctId);
            DateTime utcNow = DateTime.UtcNow;
            SecurityContextSecurityToken token = new SecurityContextSecurityToken(new UniqueId(sctId), key, utcNow, utcNow + TimeSpan.FromDays(36500.0));
            BinarySecretSecurityToken token2 = new BinarySecretSecurityToken(key);
            SecurityStandardsManager standardsManager = CreateStandardsManager(protocolVersion);
            RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(standardsManager) {
                TokenType = standardsManager.SecureConversationDriver.TokenTypeUri,
                RequestedUnattachedReference = SecurityContextSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.External),
                RequestedAttachedReference = SecurityContextSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.Internal),
                RequestedSecurityToken = token,
                RequestedProofToken = token2
            };
            DataContractSerializer serializer = IdentifierElementSerializer(protocolVersion);
            ProtocolVersionHelper.AssertProtocolVersion(protocolVersion, typeof(CoordinationServiceSecurity), "CreateIssuedToken");
            switch (protocolVersion)
            {
                case ProtocolVersion.Version10:
                    response.SetAppliesTo<IdentifierElement10>(new IdentifierElement10(coordinationContextId), serializer);
                    break;

                case ProtocolVersion.Version11:
                    response.SetAppliesTo<IdentifierElement11>(new IdentifierElement11(coordinationContextId), serializer);
                    break;
            }
            response.MakeReadOnly();
            if (DebugTrace.Verbose)
            {
                DebugTrace.Trace(TraceLevel.Verbose, "Created issued token with id {0} for transaction {1}", sctId, transactionId);
            }
            issuedToken = response;
        }
        public SecurityContextSecurityToken CreateSecurityContextFromCookie(byte[] encodedCookie, UniqueId contextId, UniqueId generation, string id, XmlDictionaryReaderQuotas quotas)
        {
            byte[] cookie = null;

            try
            {
                cookie = this.securityStateEncoder.DecodeSecurityState(encodedCookie);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                OnInvalidCookieFailure(SR.GetString(SR.SctCookieBlobDecodeFailure), e);
            }
            SecurityContextSecurityToken sct = DeserializeContext(cookie, encodedCookie, id, quotas);

            if (sct.ContextId != contextId)
            {
                OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "ContextId"));
            }
            if (sct.KeyGeneration != generation)
            {
                OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "KeyGeneration"));
            }

            return(sct);
        }
 internal SecurityContextSecurityToken(SecurityContextSecurityToken sourceToken, string id, byte[] key, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
     : base()
 {
     _id = id;
     this.Initialize(sourceToken._contextId, key, sourceToken.ValidFrom, sourceToken.ValidTo, authorizationPolicies, sourceToken._isCookieMode, keyGeneration, keyEffectiveTime, keyExpirationTime);
     _cookieBlob = sourceToken._cookieBlob;
     _bootstrapMessageProperty = (sourceToken._bootstrapMessageProperty == null) ? null : (SecurityMessageProperty)sourceToken.BootstrapMessageProperty.CreateCopy();
 }
 private SecurityContextSecurityToken(SecurityContextSecurityToken from)
 {
     ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = System.IdentityModel.SecurityUtils.CloneAuthorizationPoliciesIfNecessary(from._authorizationPolicies);
     _id = from._id;
     this.Initialize(from._contextId, from._key, from._tokenEffectiveTime, from._tokenExpirationTime, authorizationPolicies, from._isCookieMode, from._keyGeneration, from._keyEffectiveTime, from._keyExpirationTime);
     _cookieBlob = from._cookieBlob;
     _bootstrapMessageProperty = (from._bootstrapMessageProperty == null) ? null : (SecurityMessageProperty)from.BootstrapMessageProperty.CreateCopy();
 }
		public void ConstructorNullPolicies () // allowed
		{
			SecurityContextSecurityToken sct = new SecurityContextSecurityToken (
				new UniqueId (), "urn:id-1", new byte [32],
				DateTime.MinValue, DateTime.MaxValue,
				null);
			Assert.IsNotNull (sct.AuthorizationPolicies, "#1");
		}
 public void SetServiceToken(SecurityContextSecurityToken token)
 {
     if (token == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
     }
     this.serviceToken = token;
     this.isNegotiationCompleted = true;
 }
Exemple #12
0
        private SecurityContextSecurityToken(SecurityContextSecurityToken from)
        {
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = System.IdentityModel.SecurityUtils.CloneAuthorizationPoliciesIfNecessary(from.authorizationPolicies);

            this.id = from.id;
            this.Initialize(from.contextId, from.key, from.tokenEffectiveTime, from.tokenExpirationTime, authorizationPolicies, from.isCookieMode, from.keyGeneration, from.keyEffectiveTime, from.keyExpirationTime);
            this.cookieBlob = from.cookieBlob;
            this.bootstrapMessageProperty = (from.bootstrapMessageProperty == null) ? null : ((SecurityMessageProperty)from.BootstrapMessageProperty.CreateCopy());
        }
        protected override ReadOnlyCollection <IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            SecurityContextSecurityToken sct = (SecurityContextSecurityToken)token;

            if (!this.IsTimeValid(sct))
            {
                this.ThrowExpiredContextFaultException(sct.ContextId, sct);
            }
            return(sct.AuthorizationPolicies);
        }
		public Collection<SecurityContextSecurityToken> GetAllContexts (UniqueId contextId)
		{
			Table table;
			if (!cache.TryGetValue (contextId, out table))
				return new Collection<SecurityContextSecurityToken> ();
			SecurityContextSecurityToken [] arr =
				new SecurityContextSecurityToken [table.Count];
			table.Values.CopyTo (arr, 0);
			return new Collection<SecurityContextSecurityToken> (arr);
		}
        /// <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();
        }
 internal ReadOnlyCollection<IAuthorizationPolicy> GetInitiatorTokenAuthorizationPolicies(bool includeTransportToken, SecurityContextSecurityToken supportingSessionTokenToExclude)
 {
     if (!this.HasIncomingSupportingTokens)
     {
         if (((this.transportToken != null) && (this.initiatorToken == null)) && (this.protectionToken == null))
         {
             if (includeTransportToken && (this.transportToken.SecurityTokenPolicies != null))
             {
                 return this.transportToken.SecurityTokenPolicies;
             }
             return EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
         }
         if (((this.transportToken == null) && (this.initiatorToken != null)) && (this.protectionToken == null))
         {
             return (this.initiatorToken.SecurityTokenPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance);
         }
         if (((this.transportToken == null) && (this.initiatorToken == null)) && (this.protectionToken != null))
         {
             return (this.protectionToken.SecurityTokenPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance);
         }
     }
     Collection<IAuthorizationPolicy> policies = new Collection<IAuthorizationPolicy>();
     if (includeTransportToken)
     {
         this.AddAuthorizationPolicies(this.transportToken, policies);
     }
     this.AddAuthorizationPolicies(this.initiatorToken, policies);
     this.AddAuthorizationPolicies(this.protectionToken, policies);
     if (this.HasIncomingSupportingTokens)
     {
         for (int i = 0; i < this.incomingSupportingTokens.Count; i++)
         {
             if (supportingSessionTokenToExclude != null)
             {
                 SecurityContextSecurityToken securityToken = this.incomingSupportingTokens[i].SecurityToken as SecurityContextSecurityToken;
                 if ((securityToken != null) && (securityToken.ContextId == supportingSessionTokenToExclude.ContextId))
                 {
                     continue;
                 }
             }
             switch (this.incomingSupportingTokens[i].SecurityTokenAttachmentMode)
             {
                 case SecurityTokenAttachmentMode.Endorsing:
                 case SecurityTokenAttachmentMode.Signed:
                 case SecurityTokenAttachmentMode.SignedEncrypted:
                 case SecurityTokenAttachmentMode.SignedEndorsing:
                     this.AddAuthorizationPolicies(this.incomingSupportingTokens[i], policies);
                     break;
             }
         }
     }
     return new ReadOnlyCollection<IAuthorizationPolicy>(policies);
 }
        public Collection <SecurityContextSecurityToken> GetAllContexts(UniqueId contextId)
        {
            Table table;

            if (!cache.TryGetValue(contextId, out table))
            {
                return(new Collection <SecurityContextSecurityToken> ());
            }
            SecurityContextSecurityToken [] arr =
                new SecurityContextSecurityToken [table.Count];
            table.Values.CopyTo(arr, 0);
            return(new Collection <SecurityContextSecurityToken> (arr));
        }
        public void AddContext(SecurityContextSecurityToken token)
        {
            //
            // WCF will cache the token first before calling the WrappedSessionSecurityTokenHandler.OnTokenIssued.
            // We need to map the claims here so we will be caching the correct token with Geneva Claims substitued
            // in place of the WCF claims.
            //
            _claimsHandler.SetPrincipalBootstrapTokensAndBindIdfxAuthPolicy(token);

            SessionSecurityTokenCacheKey key = new SessionSecurityTokenCacheKey(_claimsHandler.EndpointId, token.ContextId, token.KeyGeneration);
            SessionSecurityToken sessionToken = SecurityContextSecurityTokenHelper.ConvertSctToSessionToken(token, SecureConversationVersion.Default);
            DateTime expiryTime = DateTimeUtil.Add(sessionToken.ValidTo, _claimsHandler.SecurityTokenHandlerCollection.Configuration.MaxClockSkew);
            _tokenCache.AddOrUpdate(key, sessionToken, expiryTime);
        }
 public SecurityContextSecurityToken GetContext(UniqueId contextId, UniqueId generation)
 {
     DebugTrace.TraceEnter(this, "GetContext");
     SecurityContextSecurityToken currentSct = null;
     if (((SupportingTokenSecurityTokenResolver.currentSct != null) && (SupportingTokenSecurityTokenResolver.currentSct.ContextId == contextId)) && (SupportingTokenSecurityTokenResolver.currentSct.KeyGeneration == generation))
     {
         if (DebugTrace.Verbose)
         {
             DebugTrace.Trace(TraceLevel.Verbose, "Found SCT with matching id {0}", contextId);
         }
         currentSct = SupportingTokenSecurityTokenResolver.currentSct;
         SupportingTokenSecurityTokenResolver.currentSct = null;
     }
     DebugTrace.TraceLeave(this, "GetContext");
     return currentSct;
 }
        public bool TryAddContext(SecurityContextSecurityToken token)
        {
            Table table;

            if (!cache.TryGetValue(token.ContextId, out table))
            {
                table = new Table();
                table [token.KeyGeneration] = token;
            }
            else
            {
                if (table.ContainsKey(token.KeyGeneration))
                {
                    return(false);
                }
                table [token.KeyGeneration] = token;
            }
            return(true);
        }
        static public SecurityContextSecurityToken ConvertSessionTokenToSecurityContextSecurityToken(SessionSecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

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

            if (token.SctAuthorizationPolicy != null)
            {
                policies.Add(token.SctAuthorizationPolicy);
            }

            if (token.ClaimsPrincipal != null && token.ClaimsPrincipal.Identities != null)
            {
                policies.Add(new AuthorizationPolicy(token.ClaimsPrincipal.Identities));
            }

            byte[] key = null;
            SymmetricSecurityKey symmetricKey = token.SecurityKeys[0] as SymmetricSecurityKey;

            if (symmetricKey != null)
            {
                key = symmetricKey.GetSymmetricKey();
            }

            SecurityContextSecurityToken sct = new SecurityContextSecurityToken(
                token.ContextId,
                token.Id,
                key,
                token.ValidFrom,
                token.ValidTo,
                token.KeyGeneration,
                token.KeyEffectiveTime,
                token.KeyExpirationTime,
                policies.AsReadOnly());

            return(sct);
        }
 public bool FaultInSupportingToken(Message message)
 {
     DebugTrace.TraceEnter(this, "FaultInSupportingToken");
     bool flag = false;
     WsatRegistrationHeader header = this.ReadRegistrationHeader(message);
     if (((header == null) || (header.TransactionId == Guid.Empty)) || string.IsNullOrEmpty(header.TokenId))
     {
         if (DebugTrace.Warning)
         {
             DebugTrace.Trace(TraceLevel.Warning, "Invalid or absent RegisterInfo in register message");
         }
     }
     else
     {
         currentSct = this.DeriveToken(header.TransactionId, header.TokenId);
         flag = true;
         if (DebugTrace.Verbose)
         {
             DebugTrace.Trace(TraceLevel.Verbose, "Created SCT with id {0} for transaction {1}", header.TokenId, header.TransactionId);
         }
     }
     DebugTrace.TraceLeave(this, "FaultInSupportingToken");
     return flag;
 }
		public bool TryAddContext (SecurityContextSecurityToken token)
		{
			Table table;
			if (!cache.TryGetValue (token.ContextId, out table)) {
				table = new Table ();
				table [token.KeyGeneration] = token;
			} else {
				if (table.ContainsKey (token.KeyGeneration))
					return false;
				table [token.KeyGeneration] = token;
			}
			return true;
		}
		public void AddContext (SecurityContextSecurityToken token)
		{
			if (!TryAddContext (token))
				throw new InvalidOperationException ("Argument token is already in the cache.");
		}
 private void ThrowExpiredContextFaultException(UniqueId contextId, SecurityContextSecurityToken sct)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityContextTokenValidationException(System.ServiceModel.SR.GetString("SecurityContextExpired", new object[] { contextId, (sct.KeyGeneration == null) ? "none" : sct.KeyGeneration.ToString() })));
 }
 public void AddContext(SecurityContextSecurityToken token)
 {
     this.tokenCache.AddContext(token);
 }
		public void WriteSecurityContextSecurityToken ()
		{
			StringWriter sw = new StringWriter ();
			SecurityContextSecurityToken t = new SecurityContextSecurityToken (
				new UniqueId ("urn:unique-id:securitycontext:1"),
				"urn:securitycontext:1",
				Convert.FromBase64String ("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="),
				new DateTime (2006, 9, 26), new DateTime (2006, 9, 27));
			using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) {
				WSSecurityTokenSerializer.DefaultInstance.WriteToken (w, t);
			}
			Assert.AreEqual ("<c:SecurityContextToken u:Id=\"urn:securitycontext:1\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:c=\"http://schemas.xmlsoap.org/ws/2005/02/sc\"><c:Identifier>urn:unique-id:securitycontext:1</c:Identifier></c:SecurityContextToken>", sw.ToString ());
		}
        static public SessionSecurityToken ConvertSctToSessionToken(SecurityContextSecurityToken sct, SecureConversationVersion version)
        {
            string endpointId = String.Empty;

            for (int i = 0; i < sct.AuthorizationPolicies.Count; ++i)
            {
                EndpointAuthorizationPolicy epAuthPolicy = sct.AuthorizationPolicies[i] as EndpointAuthorizationPolicy;
                if (epAuthPolicy != null)
                {
                    endpointId = epAuthPolicy.EndpointId;
                    break;
                }
            }

            SctAuthorizationPolicy sctAuthPolicy = null;
            for (int i = 0; i < sct.AuthorizationPolicies.Count; i++)
            {
                IAuthorizationPolicy authPolicy = sct.AuthorizationPolicies[i];

                // The WCF SCT will have a SctAuthorizationPolicy that wraps the Primary Identity
                // of the bootstrap token. This is required for SCT renewal scenarios. Write the 
                // SctAuthorizationPolicy if one is available.
                sctAuthPolicy = authPolicy as SctAuthorizationPolicy;
                if (sctAuthPolicy != null)
                {
                    break;
                }
            }

            ClaimsPrincipal claimsPrincipal = null;
            // these can be empty in transport security
            if (sct.AuthorizationPolicies != null && sct.AuthorizationPolicies.Count > 0)
            {
                AuthorizationPolicy ap = null;
                for (int i = 0; i < sct.AuthorizationPolicies.Count; ++i)
                {
                    ap = sct.AuthorizationPolicies[i] as AuthorizationPolicy;
                    if (ap != null)
                    {
                        // We should have exactly one IAuthorizationPolicy of type AuthorizationPolicy.
                        break;
                    }
                }
                if (ap != null)
                {
                    if (ap.IdentityCollection != null)
                    {
                        claimsPrincipal = new ClaimsPrincipal(ap.IdentityCollection);
                    }
                }
            }

            if (claimsPrincipal == null)
            {
                // When _securityContextTokenWrapper is true, this implies WCF.
                // Authpolicies not found occurs when the SCT represents a bootstrap nego that is used obtain a key
                // for the outer or actual SCT {unfortunate but true and we haven't found a way to distinguish this otherwise}.
                // So return an empty ClaimsPrincipal so that when written on wire in cookie mode we DO NOT write an empty identity.
                // If we did, then when the actual bootstrap token, such as a SAML token arrives, we will add the bootstrap AND the SAML identities to the ClaimsPrincipal
                // and end up with multiple, one of them anonymous.
                // 
                claimsPrincipal = new ClaimsPrincipal();
            }

            return new SessionSecurityToken(claimsPrincipal, sct.ContextId, sct.Id, String.Empty, sct.GetKeyBytes(), endpointId, sct.ValidFrom, sct.ValidTo, sct.KeyGeneration, sct.KeyEffectiveTime, sct.KeyExpirationTime, sctAuthPolicy, new Uri(version.Namespace.Value));
        }
        Message ProcessClientKeyExchange(Message request)
        {
            // FIXME: use correct buffer size
            MessageBuffer buffer = request.CreateBufferedCopy(0x10000);
            WSTrustRequestSecurityTokenResponseReader reader =
                new WSTrustRequestSecurityTokenResponseReader(Constants.WstTlsnegoProofTokenType, buffer.CreateMessage().GetReaderAtBodyContents(), SecurityTokenSerializer, null);

            reader.Read();

            TlsServerSessionInfo tlsInfo;

            if (!sessions.TryGetValue(reader.Value.Context, out tlsInfo))
            {
                throw new SecurityNegotiationException(String.Format("The context '{0}' does not exist in this SSL negotiation manager", reader.Value.Context));
            }
            TlsServerSession tls = tlsInfo.Tls;

            AppendNegotiationMessageXml(buffer.CreateMessage().GetReaderAtBodyContents(), tlsInfo);
//Console.WriteLine (System.Text.Encoding.UTF8.GetString (tlsInfo.Messages.ToArray ()));

            tls.ProcessClientKeyExchange(reader.Value.BinaryExchange.Value);

            byte [] serverFinished = tls.ProcessServerFinished();

            // The shared key is computed as recommended in WS-Trust:
            // P_SHA1(encrypted_key,SHA1(exc14n(RST..RSTRs))+"CK-HASH")
            byte [] hash          = SHA1.Create().ComputeHash(tlsInfo.Messages.ToArray());
            byte [] key           = tls.CreateHash(tls.MasterSecret, hash, "CK-HASH");
            byte [] keyTlsApplied = tls.ProcessApplicationData(key);
            foreach (byte b in hash)
            {
                Console.Write("{0:X02} ", b);
            }
            Console.WriteLine();
            foreach (byte b in key)
            {
                Console.Write("{0:X02} ", b);
            }
            Console.WriteLine();

            WstRequestSecurityTokenResponseCollection col =
                new WstRequestSecurityTokenResponseCollection();
            WstRequestSecurityTokenResponse rstr =
                new WstRequestSecurityTokenResponse(SecurityTokenSerializer);

            rstr.Context   = reader.Value.Context;
            rstr.TokenType = Constants.WsscContextToken;
            DateTime from = DateTime.Now;
            // FIXME: not sure if arbitrary key is used here.
            SecurityContextSecurityToken sct = SecurityContextSecurityToken.CreateCookieSecurityContextToken(
                // Create a new context.
                // (do not use sslnego context here.)
                new UniqueId(),
                "uuid-" + Guid.NewGuid(),
                key,
                from,
                // FIXME: use LocalServiceSecuritySettings.NegotiationTimeout
                from.AddHours(8),
                null,
                owner.Manager.ServiceCredentials.SecureConversationAuthentication.SecurityStateEncoder);

            rstr.RequestedSecurityToken = sct;
            // without this ProcessApplicationData(), .NET seems
            // to fail recovering the key.
            rstr.RequestedProofToken          = keyTlsApplied;
            rstr.RequestedAttachedReference   = new LocalIdKeyIdentifierClause(sct.Id);
            rstr.RequestedUnattachedReference = new SecurityContextKeyIdentifierClause(sct.ContextId, null);
            WstLifetime lt = new WstLifetime();

            lt.Created                = from;
            lt.Expires                = from.Add(SecurityBindingElement.LocalServiceSettings.IssuedCookieLifetime);
            rstr.Lifetime             = lt;
            rstr.BinaryExchange       = new WstBinaryExchange(Constants.WstBinaryExchangeValueTls);
            rstr.BinaryExchange.Value = serverFinished;

            col.Responses.Add(rstr);

            // Authenticator is mandatory for MS sslnego.
            rstr               = new WstRequestSecurityTokenResponse(SecurityTokenSerializer);
            rstr.Context       = reader.Value.Context;
            rstr.Authenticator = tls.CreateHash(key, hash, "AUTH-HASH");
            col.Responses.Add(rstr);

            sessions.Remove(reader.Value.Context);

            // FIXME: get correct tokenRequestor address (probably identity authorized?)
            if (owner.IssuedSecurityTokenHandler != null)
            {
                owner.IssuedSecurityTokenHandler(sct, request.Headers.ReplyTo);
            }

            return(Message.CreateMessage(request.Version, Constants.WstIssueReplyAction, col));
        }
 private void ThrowExpiredContextFaultException(UniqueId contextId, SecurityContextSecurityToken sct)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityContextTokenValidationException(System.ServiceModel.SR.GetString("SecurityContextExpired", new object[] { contextId, (sct.KeyGeneration == null) ? "none" : sct.KeyGeneration.ToString() })));
 }
		void WriteSecurityContextSecurityToken (XmlWriter w, SecurityContextSecurityToken token)
		{
			string ns = Constants.WsscNamespace;
			w.WriteStartElement ("c", "SecurityContextToken", ns);
			w.WriteAttributeString ("u", "Id", Constants.WsuNamespace, token.Id);
			w.WriteElementString ("Identifier", ns, token.ContextId.ToString ());
			// FIXME: add Cookie output (from CreateCookieSecurityContextToken() method)
			if (token.Cookie != null)
				w.WriteElementString ("dnse", "Cookie", Constants.MSTlsnegoTokenContent, Convert.ToBase64String (token.Cookie));
			w.WriteEndElement ();
		}
 void ThrowExpiredContextFaultException(UniqueId contextId, SecurityContextSecurityToken sct)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityContextTokenValidationException(SR.GetString(SR.SecurityContextExpired, contextId, sct.KeyGeneration == null ? "none" : sct.KeyGeneration.ToString())));
 }
		public void WriteSecurityContextKeyIdentifierClause2 ()
		{
			StringWriter sw = new StringWriter ();
			MySslParameters tp = new MySslParameters ();
			SecurityContextSecurityToken sct =
				new SecurityContextSecurityToken (new UniqueId ("urn:foo:1"), "urn:foo:2", new byte [32], DateTime.MinValue, DateTime.MaxValue);
			SecurityKeyIdentifierClause ic =
				tp.CallCreateKeyIdentifierClause (sct, SecurityTokenReferenceStyle.Internal);
			using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) {
				WSSecurityTokenSerializer.DefaultInstance.WriteKeyIdentifierClause (w, ic);
			}
			Assert.AreEqual (@"<o:SecurityTokenReference xmlns:o=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd""><o:Reference URI=""#urn:foo:2"" /></o:SecurityTokenReference>", sw.ToString (), "#1");
			XmlReader reader = XmlReader.Create (new StringReader (sw.ToString ()));
			ic = WSSecurityTokenSerializer.DefaultInstance.ReadKeyIdentifierClause (reader) as LocalIdKeyIdentifierClause;
			Assert.IsNotNull (ic, "#2");
		}
        public static SecurityContextSecurityToken ResolveCookie(byte [] bytes, byte [] cookie)
        {
            string   id           = null;
            UniqueId context      = null;
            DateTime validFrom    = DateTime.MinValue,
                     validTo      = DateTime.MaxValue,
                     keyEffective = DateTime.MinValue,
                     keyExpired   = DateTime.MaxValue;

            byte []               key    = null;
            X509Certificate2      cert   = null;
            X500DistinguishedName issuer = null;

            XmlDictionary dic = new XmlDictionary();

            for (int i = 0; i < 30; i++)
            {
                dic.Add("n" + i);
            }
            // FIXME: create proper quotas
            XmlDictionaryReaderQuotas quotas =
                new XmlDictionaryReaderQuotas();
            XmlDictionaryReader cr = XmlDictionaryReader.CreateBinaryReader(bytes, 0, bytes.Length, dic, quotas);

            cr.MoveToContent(); // -> n1
            cr.ReadStartElement("n0", String.Empty);
            do
            {
                cr.MoveToContent();
                if (cr.NodeType == XmlNodeType.EndElement)
                {
                    break;
                }
                if (cr.NodeType != XmlNodeType.Element)
                {
                    throw new Exception("Unxpected non-element content:" + cr.NodeType);
                }

                switch (cr.Name)
                {
                case "n1":
                    // FIXME: some integer here
                    int n1 = cr.ReadElementContentAsInt();
                    if (n1 != 1)
                    {
                        throw new Exception("INTERNAL ERROR: there was unexpected n2 content: " + n1);
                    }
                    break;

                case "n2":
                    context = cr.ReadElementContentAsUniqueId();
                    break;

                case "n3":
                    id = cr.ReadElementContentAsString();
                    break;

                case "n4":
                    key = cr.ReadElementContentAsBase64();
                    break;

                case "n7":
                    validFrom = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n8":
                    validTo = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n10":
                    keyEffective = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n11":
                    keyExpired = new DateTime(cr.ReadElementContentAsLong());
                    break;

                case "n13":
                    // <n18>X509Certificate</n18>
                    cr.Read();
                    cr.MoveToContent();
                    cert = new X509Certificate2(cr.ReadElementContentAsBase64());
                    cr.ReadEndElement();
                    break;

                case "n15":
                    // <n16><n24 n25="IssuerName" /></n16>
                    cr.Read();
                    cr.ReadStartElement("n16", String.Empty);
                    issuer = new X500DistinguishedName(cr.GetAttribute("n25"));
                    bool empty = cr.IsEmptyElement;
                    cr.ReadStartElement("n24", String.Empty);
                    if (!empty)
                    {
                        cr.ReadEndElement(); // n24
                    }
                    cr.ReadEndElement();     // n16
                    cr.ReadEndElement();     // n15
                    break;

                default:
                    throw new Exception("INTERNAL ERROR: there was an unhandled element: " + cr.Name);
                }
            }while (true);

            SecurityContextSecurityToken sct = new SecurityContextSecurityToken(
                context, id, key, validFrom, validTo,
                null, keyEffective, keyExpired, null);

            sct.Cookie = cookie;
            return(sct);
        }
 internal SecurityContextSecurityToken(SecurityContextSecurityToken sourceToken, string id)
     : this(sourceToken, id, sourceToken._key, sourceToken._keyGeneration, sourceToken._keyEffectiveTime, sourceToken._keyExpirationTime, sourceToken.AuthorizationPolicies)
 {
 }
 public void AddContext(SecurityContextSecurityToken token)
 {
 }
 public void UpdateContextCachingTime(SecurityContextSecurityToken context, DateTime expirationTime)
 {
 }
 public void UpdateContextCachingTime(SecurityContextSecurityToken context, DateTime expirationTime)
 {
     this.tokenCache.UpdateContextCachingTime(context, expirationTime);
 }
 public void AddContext(SecurityContextSecurityToken token)
 {
 }
        static public SessionSecurityToken ConvertSctToSessionToken(SecurityContextSecurityToken sct, SecureConversationVersion version)
        {
            string endpointId = String.Empty;

            for (int i = 0; i < sct.AuthorizationPolicies.Count; ++i)
            {
                EndpointAuthorizationPolicy epAuthPolicy = sct.AuthorizationPolicies[i] as EndpointAuthorizationPolicy;
                if (epAuthPolicy != null)
                {
                    endpointId = epAuthPolicy.EndpointId;
                    break;
                }
            }

            SctAuthorizationPolicy sctAuthPolicy = null;

            for (int i = 0; i < sct.AuthorizationPolicies.Count; i++)
            {
                IAuthorizationPolicy authPolicy = sct.AuthorizationPolicies[i];

                // The WCF SCT will have a SctAuthorizationPolicy that wraps the Primary Identity
                // of the bootstrap token. This is required for SCT renewal scenarios. Write the
                // SctAuthorizationPolicy if one is available.
                sctAuthPolicy = authPolicy as SctAuthorizationPolicy;
                if (sctAuthPolicy != null)
                {
                    break;
                }
            }

            ClaimsPrincipal claimsPrincipal = null;

            // these can be empty in transport security
            if (sct.AuthorizationPolicies != null && sct.AuthorizationPolicies.Count > 0)
            {
                AuthorizationPolicy ap = null;
                for (int i = 0; i < sct.AuthorizationPolicies.Count; ++i)
                {
                    ap = sct.AuthorizationPolicies[i] as AuthorizationPolicy;
                    if (ap != null)
                    {
                        // We should have exactly one IAuthorizationPolicy of type AuthorizationPolicy.
                        break;
                    }
                }
                if (ap != null)
                {
                    if (ap.IdentityCollection != null)
                    {
                        claimsPrincipal = new ClaimsPrincipal(ap.IdentityCollection);
                    }
                }
            }

            if (claimsPrincipal == null)
            {
                // When _securityContextTokenWrapper is true, this implies WCF.
                // Authpolicies not found occurs when the SCT represents a bootstrap nego that is used obtain a key
                // for the outer or actual SCT {unfortunate but true and we haven't found a way to distinguish this otherwise}.
                // So return an empty ClaimsPrincipal so that when written on wire in cookie mode we DO NOT write an empty identity.
                // If we did, then when the actual bootstrap token, such as a SAML token arrives, we will add the bootstrap AND the SAML identities to the ClaimsPrincipal
                // and end up with multiple, one of them anonymous.
                //
                claimsPrincipal = new ClaimsPrincipal();
            }

            return(new SessionSecurityToken(claimsPrincipal, sct.ContextId, sct.Id, String.Empty, sct.GetKeyBytes(), endpointId, sct.ValidFrom, sct.ValidTo, sct.KeyGeneration, sct.KeyEffectiveTime, sct.KeyExpirationTime, sctAuthPolicy, new Uri(version.Namespace.Value)));
        }
 public bool TryAddContext(SecurityContextSecurityToken token)
 {
   return default(bool);
 }
 static public SessionSecurityToken ConvertSctToSessionToken(SecurityContextSecurityToken sct)
 {
     return ConvertSctToSessionToken(sct, SecureConversationVersion.Default);
 }
Exemple #43
0
        public SecurityToken GetToken(TimeSpan timeout)
        {
            TlsnegoClientSessionContext tlsctx =
                new TlsnegoClientSessionContext();
            TlsClientSession        tls = new TlsClientSession(IssuerAddress.Uri.ToString(), client_certificate, owner.Manager.ClientCredentials.ServiceCertificate.Authentication);
            WstRequestSecurityToken rst =
                new WstRequestSecurityToken();
            string contextId = rst.Context;

            // send ClientHello
            rst.BinaryExchange       = new WstBinaryExchange(Constants.WstBinaryExchangeValueTls);
            rst.BinaryExchange.Value = tls.ProcessClientHello();

            Message request = Message.CreateMessage(IssuerBinding.MessageVersion, Constants.WstIssueAction, rst);

            request.Headers.MessageId = new UniqueId();
            request.Headers.ReplyTo   = new EndpointAddress(Constants.WsaAnonymousUri);
            request.Headers.To        = TargetAddress.Uri;
            MessageBuffer buffer = request.CreateBufferedCopy(0x10000);

            tlsctx.StoreMessage(buffer.CreateMessage().GetReaderAtBodyContents());
            Message response = proxy.Issue(buffer.CreateMessage());

            // FIXME: use correct limitation
            buffer = response.CreateBufferedCopy(0x10000);
            tlsctx.StoreMessage(buffer.CreateMessage().GetReaderAtBodyContents());

            // receive ServerHello
            WSTrustRequestSecurityTokenResponseReader reader =
                new WSTrustRequestSecurityTokenResponseReader(Constants.WstTlsnegoProofTokenType, buffer.CreateMessage().GetReaderAtBodyContents(), SecurityTokenSerializer, null);

            reader.Read();
            if (reader.Value.RequestedSecurityToken != null)
            {
                return(reader.Value.RequestedSecurityToken);
            }

            tls.ProcessServerHello(reader.Value.BinaryExchange.Value);

            // send ClientKeyExchange
            WstRequestSecurityTokenResponse rstr =
                new WstRequestSecurityTokenResponse(SecurityTokenSerializer);

            rstr.Context              = reader.Value.Context;
            rstr.BinaryExchange       = new WstBinaryExchange(Constants.WstBinaryExchangeValueTls);
            rstr.BinaryExchange.Value = tls.ProcessClientKeyExchange();

            request = Message.CreateMessage(IssuerBinding.MessageVersion, Constants.WstIssueReplyAction, rstr);
            request.Headers.ReplyTo = new EndpointAddress(Constants.WsaAnonymousUri);
            request.Headers.To      = TargetAddress.Uri;

            buffer = request.CreateBufferedCopy(0x10000);
            tlsctx.StoreMessage(buffer.CreateMessage().GetReaderAtBodyContents());
//Console.WriteLine (System.Text.Encoding.UTF8.GetString (tlsctx.GetC14NResults ()));

            // FIXME: regeneration of this instance is somehow required, but should not be.
            proxy = new WSTrustSecurityTokenServiceProxy(
                IssuerBinding, IssuerAddress);
            response = proxy.IssueReply(buffer.CreateMessage());
            // FIXME: use correct limitation
            buffer = response.CreateBufferedCopy(0x10000);

            WstRequestSecurityTokenResponseCollection coll =
                new WstRequestSecurityTokenResponseCollection();

            coll.Read(Constants.WstTlsnegoProofTokenType, buffer.CreateMessage().GetReaderAtBodyContents(), SecurityTokenSerializer, null);
            if (coll.Responses.Count != 2)
            {
                throw new SecurityNegotiationException(String.Format("Expected response is RequestSecurityTokenResponseCollection which contains two RequestSecurityTokenResponse items, but it actually contains {0} items", coll.Responses.Count));
            }

            WstRequestSecurityTokenResponse r = coll.Responses [0];

            tls.ProcessServerFinished(r.BinaryExchange.Value);
            SecurityContextSecurityToken sctSrc =
                r.RequestedSecurityToken;

#if false // FIXME: should this final RSTR included in RSTRC considered too?
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            using (XmlDictionaryWriter dw = XmlDictionaryWriter.CreateDictionaryWriter(doc.CreateNavigator().AppendChild()))
            {
                if (r == null)
                {
                    throw new Exception("r");
                }
                if (dw == null)
                {
                    throw new Exception("dw");
                }
                r.WriteBodyContents(dw);
            }
            tlsctx.StoreMessage(XmlDictionaryReader.CreateDictionaryReader(new XmlNodeReader(doc)));
#endif

            // the RequestedProofToken is represented as 32 bytes
            // of TLS ApplicationData.
            // - According to WSE2 doc, it is *the* key, but not
            //   sure it also applies to WCF.
            // - WSS4J also seems to store the encryped shared key.
            // - (Important) It seems that without tls decryption,
            //   .NET fails to recover the key.
            byte [] proof = tls.ProcessApplicationData(
                (byte [])r.RequestedProofToken);
            byte [] key = proof;

            // Authenticate token.

            byte [] actual = coll.Responses [1].Authenticator;
            if (actual == null)
            {
                throw new SecurityNegotiationException("Token authenticator is expected in the RequestSecurityTokenResponse but not found.");
            }

            if (coll.Responses [0].Context != contextId)
            {
                throw new SecurityNegotiationException("The context Id does not match with that of the corresponding token authenticator.");
            }

            // H = sha1(exc14n(RST..RSTRs))
            byte [] hash     = SHA1.Create().ComputeHash(tlsctx.GetC14NResults());
            byte [] referent = tls.CreateHash(key, hash, "AUTH-HASH");
            Console.WriteLine(System.Text.Encoding.ASCII.GetString(tlsctx.GetC14NResults()));
            Console.Write("Hash: ");
            foreach (byte b in hash)
            {
                Console.Write("{0:X02} ", b);
            }
            Console.WriteLine();
            Console.Write("Referent: ");
            foreach (byte b in referent)
            {
                Console.Write("{0:X02} ", b);
            }
            Console.WriteLine();
            Console.Write("Actual: ");
            foreach (byte b in actual)
            {
                Console.Write("{0:X02} ", b);
            }
            Console.WriteLine();
            Console.Write("Proof: ");
            foreach (byte b in proof)
            {
                Console.Write("{0:X02} ", b);
            }
            Console.WriteLine();
            bool mismatch = referent.Length != actual.Length;
            if (!mismatch)
            {
                for (int i = 0; i < referent.Length; i++)
                {
                    if (referent [i] != actual [i])
                    {
                        mismatch = true;
                    }
                }
            }

            if (mismatch)
            {
                throw new SecurityNegotiationException("The CombinedHash does not match the expected value.");
            }

            return(sctSrc);
        }
        static public SecurityContextSecurityToken ConvertSessionTokenToSecurityContextSecurityToken(SessionSecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }
            
            List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
            if (token.SctAuthorizationPolicy != null)
            {
                policies.Add(token.SctAuthorizationPolicy);
            }

            if (token.ClaimsPrincipal != null && token.ClaimsPrincipal.Identities != null)
            {
                policies.Add(new AuthorizationPolicy(token.ClaimsPrincipal.Identities));
            }

            byte[] key = null;
            SymmetricSecurityKey symmetricKey = token.SecurityKeys[0] as SymmetricSecurityKey;
            if (symmetricKey != null)
            {
                key = symmetricKey.GetSymmetricKey();
            }

            SecurityContextSecurityToken sct = new SecurityContextSecurityToken(
                token.ContextId,
                 token.Id,
                 key, 
                 token.ValidFrom, 
                 token.ValidTo, 
                 token.KeyGeneration, 
                 token.KeyEffectiveTime, 
                 token.KeyExpirationTime,
                 policies.AsReadOnly());

            return sct;
        }
 public void UpdateContextCachingTime(SecurityContextSecurityToken context, DateTime expirationTime)
 {
 }
 public void UpdateContextCachingTime(SecurityContextSecurityToken context, DateTime expirationTime)
 {
     throw new NotImplementedException();
 }
        internal ReadOnlyCollection<IAuthorizationPolicy> GetInitiatorTokenAuthorizationPolicies(bool includeTransportToken, SecurityContextSecurityToken supportingSessionTokenToExclude)
        {
            // fast path
            if (!this.HasIncomingSupportingTokens)
            {
                if (_transportToken != null && _initiatorToken == null && _protectionToken == null)
                {
                    if (includeTransportToken && _transportToken.SecurityTokenPolicies != null)
                    {
                        return _transportToken.SecurityTokenPolicies;
                    }
                    else
                    {
                        return EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
                    }
                }
                else if (_transportToken == null && _initiatorToken != null && _protectionToken == null)
                {
                    return _initiatorToken.SecurityTokenPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
                }
                else if (_transportToken == null && _initiatorToken == null && _protectionToken != null)
                {
                    return _protectionToken.SecurityTokenPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance;
                }
            }

            Collection<IAuthorizationPolicy> policies = new Collection<IAuthorizationPolicy>();
            if (includeTransportToken)
            {
                AddAuthorizationPolicies(_transportToken, policies);
            }
            AddAuthorizationPolicies(_initiatorToken, policies);
            AddAuthorizationPolicies(_protectionToken, policies);
            if (this.HasIncomingSupportingTokens)
            {
                for (int i = 0; i < _incomingSupportingTokens.Count; ++i)
                {
                    if (supportingSessionTokenToExclude != null)
                    {
                        SecurityContextSecurityToken sct = _incomingSupportingTokens[i].SecurityToken as SecurityContextSecurityToken;
                        if (sct != null && sct.ContextId == supportingSessionTokenToExclude.ContextId)
                        {
                            continue;
                        }
                    }
                    SecurityTokenAttachmentMode attachmentMode = _incomingSupportingTokens[i].SecurityTokenAttachmentMode;
                    // a safety net in case more attachment modes get added to the product without 
                    // reviewing this code.
                    if (attachmentMode == SecurityTokenAttachmentMode.Endorsing
                        || attachmentMode == SecurityTokenAttachmentMode.Signed
                        || attachmentMode == SecurityTokenAttachmentMode.SignedEncrypted
                        || attachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)
                    {
                        AddAuthorizationPolicies(_incomingSupportingTokens[i], policies);
                    }
                }
            }
            return new ReadOnlyCollection<IAuthorizationPolicy>(policies);
        }
        private bool IsTimeValid(SecurityContextSecurityToken sct)
        {
            DateTime utcNow = DateTime.UtcNow;

            return(((sct.ValidFrom <= utcNow) && (sct.ValidTo >= utcNow)) && (sct.KeyEffectiveTime <= utcNow));
        }
 protected override void WriteGeneration(XmlDictionaryWriter writer, SecurityContextSecurityToken sct)
 {
     if (sct.KeyGeneration != null)
     {
         writer.WriteStartElement(DXD.SecureConversationDec2005Dictionary.Prefix.Value, DXD.SecureConversationDec2005Dictionary.Instance, DXD.SecureConversationDec2005Dictionary.Namespace);
         XmlHelper.WriteStringAsUniqueId(writer, sct.KeyGeneration);
         writer.WriteEndElement();
     }
 }
		public void UpdateContextCachingTime (SecurityContextSecurityToken context, DateTime expirationTime)
		{
			throw new NotImplementedException ();
		}
		public static SecurityContextSecurityToken ResolveCookie (byte [] bytes, byte [] cookie)
		{
			string id = null;
			UniqueId context = null;
			DateTime validFrom = DateTime.MinValue,
				 validTo = DateTime.MaxValue,
				 keyEffective = DateTime.MinValue,
				 keyExpired = DateTime.MaxValue;
			byte [] key = null;
			X509Certificate2 cert = null;
			X500DistinguishedName issuer = null;

			XmlDictionary dic = new XmlDictionary ();
			for (int i = 0; i < 30; i++)
				dic.Add ("n" + i);
			// FIXME: create proper quotas
			XmlDictionaryReaderQuotas quotas =
				new XmlDictionaryReaderQuotas ();
			XmlDictionaryReader cr = XmlDictionaryReader.CreateBinaryReader (bytes, 0, bytes.Length, dic, quotas);

			cr.MoveToContent (); // -> n1
			cr.ReadStartElement ("n0", String.Empty);
			do {
				cr.MoveToContent ();
				if (cr.NodeType == XmlNodeType.EndElement)
					break;
				if (cr.NodeType != XmlNodeType.Element)
					throw new Exception ("Unxpected non-element content:" + cr.NodeType);

				switch (cr.Name) {
				case "n1":
					// FIXME: some integer here
					int n1 = cr.ReadElementContentAsInt ();
					if (n1 != 1)
						throw new Exception ("INTERNAL ERROR: there was unexpected n2 content: " + n1);
					break;
				case "n2":
					context = cr.ReadElementContentAsUniqueId ();
					break;
				case "n3":
					id = cr.ReadElementContentAsString ();
					break;
				case "n4":
					key = cr.ReadElementContentAsBase64 ();
					break;
				case "n7":
					validFrom = new DateTime (cr.ReadElementContentAsLong ());
					break;
				case "n8":
					validTo = new DateTime (cr.ReadElementContentAsLong ());
					break;
				case "n10":
					keyEffective = new DateTime (cr.ReadElementContentAsLong ());
					break;
				case "n11":
					keyExpired = new DateTime (cr.ReadElementContentAsLong ());
					break;
				case "n13":
					// <n18>X509Certificate</n18>
					cr.Read ();
					cr.MoveToContent ();
					cert = new X509Certificate2 (cr.ReadElementContentAsBase64 ());
					cr.ReadEndElement ();
					break;
				case "n15":
					// <n16><n24 n25="IssuerName" /></n16>
					cr.Read ();
					cr.ReadStartElement ("n16", String.Empty);
					issuer = new X500DistinguishedName (cr.GetAttribute ("n25"));
					bool empty = cr.IsEmptyElement;
					cr.ReadStartElement ("n24", String.Empty);
					if (!empty)
						cr.ReadEndElement (); // n24
					cr.ReadEndElement (); // n16
					cr.ReadEndElement (); // n15
					break;
				default:
					throw new Exception ("INTERNAL ERROR: there was an unhandled element: " + cr.Name);
				}
			} while (true);

			SecurityContextSecurityToken sct = new SecurityContextSecurityToken (
				context, id, key, validFrom, validTo,
				null, keyEffective, keyExpired, null);
			sct.Cookie = cookie;
			return sct;
		}
 public bool TryAddContext(SecurityContextSecurityToken token)
 {
     return(default(bool));
 }
 public bool TryAddContext(SecurityContextSecurityToken token)
 {
     return(this.tokenCache.TryAddContext(token));
 }
Exemple #54
0
 internal SecurityContextSecurityToken(SecurityContextSecurityToken sourceToken, string id) : this(sourceToken, id, sourceToken.key, sourceToken.keyGeneration, sourceToken.keyEffectiveTime, sourceToken.keyExpirationTime, sourceToken.AuthorizationPolicies)
 {
 }
 static public SessionSecurityToken ConvertSctToSessionToken(SecurityContextSecurityToken sct)
 {
     return(ConvertSctToSessionToken(sct, SecureConversationVersion.Default));
 }
 public bool TryAddContext(SecurityContextSecurityToken token)
 {
     return this.tokenCache.TryAddContext(token);
 }
 private bool IsTimeValid(SecurityContextSecurityToken sct)
 {
     DateTime utcNow = DateTime.UtcNow;
     return (((sct.ValidFrom <= utcNow) && (sct.ValidTo >= utcNow)) && (sct.KeyEffectiveTime <= utcNow));
 }