Exemplo n.º 1
0
        private EncryptedSharedFolderData Encrypt(RequestedToken requestedToken, SharedFolderData sharedFolderData)
        {
            XmlElement xmlElement;

            try
            {
                xmlElement = sharedFolderData.SerializeToXmlElement();
            }
            catch (InvalidOperationException innerException)
            {
                throw new UnableToGenerateEncryptedSharedFolderDataException(innerException);
            }
            XmlElement encryptedData;

            try
            {
                encryptedData = SymmetricEncryptedXml.Encrypt(xmlElement, requestedToken.ProofToken);
            }
            catch (CryptographicException innerException2)
            {
                throw new UnableToGenerateEncryptedSharedFolderDataException(innerException2);
            }
            return(new EncryptedSharedFolderData
            {
                Token = new EncryptedDataContainer
                {
                    EncryptedData = requestedToken.SecurityToken
                },
                Data = new EncryptedDataContainer
                {
                    EncryptedData = encryptedData
                }
            });
        }
Exemplo n.º 2
0
        private RequestedToken GetDelegationToken(ADUser user, Uri target, SecurityTokenService securityTokenService)
        {
            RequestedToken result;

            try
            {
                DelegationTokenRequest request = new DelegationTokenRequest
                {
                    FederatedIdentity = user.GetFederatedIdentity(),
                    EmailAddress      = user.GetFederatedSmtpAddress().ToString(),
                    Target            = new TokenTarget(target),
                    Offer             = TestFederationTrust.TokenOffer
                };
                RequestedToken requestedToken = securityTokenService.IssueToken(request);
                this.Log(EventTypeEnumeration.Success, TestFederationTrust.TestFederationTrustEventId.TokenRequest, Strings.DelegationTokenRequestSuccess);
                result = requestedToken;
            }
            catch (LocalizedException ex)
            {
                this.Log(EventTypeEnumeration.Error, TestFederationTrust.TestFederationTrustEventId.TokenRequest, Strings.TokenRequestFailed);
                base.WriteVerbose(Strings.FailureAndReason(Strings.TokenRequestFailed.ToString(), ex.ToString()));
                result = null;
            }
            return(result);
        }
        protected override SecurityToken EndGetTokenCore(IAsyncResult result)
        {
            RmsOperationType rmsOperationType = this.offer.Equals(Offer.IPCCertificationSTS) ? RmsOperationType.AcquireB2BRac : RmsOperationType.AcquireB2BLicense;

            if (this.cachedSecurityToken != null)
            {
                this.latencyTracker.BeginTrackRmsLatency(rmsOperationType);
                return(this.cachedSecurityToken);
            }
            RequestedToken rt = this.securityTokenService.EndIssueToken(result);

            this.latencyTracker.EndAndBeginTrackRmsLatency(RmsOperationType.RequestDelegationToken, rmsOperationType);
            this.cachedSecurityToken = SamlSecurityTokenProvider.CreateToken(rt);
            return(this.cachedSecurityToken);
        }
Exemplo n.º 4
0
        public static ProxyAuthenticator Create(RequestedToken token, SmtpAddress sharingKey, string messageId)
        {
            ProxyAuthenticator.SecurityTracer.TraceDebug(0L, "{0}: creating ProxyAuthenticator for WS-Security", new object[]
            {
                TraceContext.Get()
            });
            XmlElement xmlElement = null;

            if (sharingKey != SmtpAddress.Empty)
            {
                xmlElement = SharingKeyHandler.Encrypt(sharingKey, token.ProofToken);
            }
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(token);

            if (xmlElement != null)
            {
                soapHttpClientAuthenticator.AdditionalSoapHeaders.Add(new SharingSecurityHeader(xmlElement));
            }
            ProxyAuthenticator.SetMessageId(soapHttpClientAuthenticator, messageId);
            return(new ProxyAuthenticator(soapHttpClientAuthenticator, AuthenticatorType.WSSecurity));
        }
Exemplo n.º 5
0
 private void ValidateToken(RequestedToken requestedToken, TokenValidator tokenValidator)
 {
     try
     {
         TokenValidationResults tokenValidationResults = tokenValidator.ValidateToken(requestedToken.SecurityToken, TestFederationTrust.TokenOffer);
         if (tokenValidationResults.Result == TokenValidationResult.Valid)
         {
             this.Log(EventTypeEnumeration.Success, TestFederationTrust.TestFederationTrustEventId.TokenValidation, Strings.DelegationTokenValidationSuccess);
         }
         else
         {
             this.Log(EventTypeEnumeration.Error, TestFederationTrust.TestFederationTrustEventId.TokenValidation, Strings.TokenValidationFailed);
             base.WriteVerbose(Strings.FailureAndReason(Strings.TokenValidationFailed.ToString(), tokenValidationResults.Result.ToString()));
         }
     }
     catch (LocalizedException ex)
     {
         this.Log(EventTypeEnumeration.Error, TestFederationTrust.TestFederationTrustEventId.TokenValidation, Strings.TokenValidationFailed);
         base.WriteVerbose(Strings.FailureAndReason(Strings.TokenValidationFailed.ToString(), ex.ToString()));
     }
 }
 public MailboxSearchEwsClient(ExchangePrincipal principal, ADUser executingUser)
 {
     try
     {
         string url = null;
         DelegationTokenRequest request = null;
         this.Discover(principal, executingUser, out url, out request);
         RequestedToken token = this.securityTokenService.IssueToken(request);
         SoapHttpClientAuthenticator authenticator = SoapHttpClientAuthenticator.Create(token);
         this.binding     = new MailboxSearchEwsClient.MailboxSearchEwsBinding("ExchangeEDiscovery", new RemoteCertificateValidationCallback(MailboxSearchEwsClient.CertificateErrorHandler));
         this.binding.Url = url;
         this.binding.RequestServerVersionValue = MailboxSearchEwsClient.RequestServerVersionExchange2010;
         this.binding.Authenticator             = authenticator;
         this.binding.Proxy     = this.WebProxy;
         this.binding.UserAgent = "ExchangeEDiscovery";
         this.binding.Timeout   = 600000;
     }
     catch (WSTrustException ex)
     {
         ExTraceGlobals.SessionTracer.TraceError((long)this.GetHashCode(), ex.ToString());
         throw new MailboxSearchEwsFailedException(ex.Message);
     }
 }
        private static SecurityToken CreateToken(RequestedToken rt)
        {
            BinarySecretSecurityToken proofToken = new BinarySecretSecurityToken(rt.ProofToken.GetSymmetricKey());

            return(new GenericXmlSecurityToken(rt.SecurityToken, proofToken, DateTime.UtcNow, DateTime.UtcNow.AddDays(2.0), new SamlAssertionKeyIdentifierClause(rt.SecurityTokenReference.InnerText), new SamlAssertionKeyIdentifierClause(rt.RequestUnattachedReference.InnerText), new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>())));
        }
Exemplo n.º 8
0
        public EncryptionResults Encrypt(IExchangePrincipal mailboxOwner, IRecipientSession recipientSession, ExternalUserCollection externalUserCollection, ValidRecipient[] recipients, string sender, string containerClass, string folderId, IFrontEndLocator frontEndLocator)
        {
            SharingDataType sharingDataType = SharingDataType.FromContainerClass(containerClass);

            if (sharingDataType == null || !sharingDataType.IsExternallySharable)
            {
                throw new ArgumentOutOfRangeException("containerClass");
            }
            ADUser aduser = DirectoryHelper.ReadADRecipient(mailboxOwner.MailboxInfo.MailboxGuid, mailboxOwner.MailboxInfo.IsArchive, recipientSession) as ADUser;

            if (aduser == null)
            {
                SharedFolderDataEncryption.Tracer.TraceError <SharedFolderDataEncryption, string>((long)this.GetHashCode(), "{0}: The Active Directory user was not found. Sender={1}.", this, sender);
                throw new ObjectNotFoundException(ServerStrings.ADUserNotFound);
            }
            ProxyAddress item = new SmtpProxyAddress(sender, false);

            if (!aduser.EmailAddresses.Contains(item))
            {
                SharedFolderDataEncryption.Tracer.TraceError <SharedFolderDataEncryption, string>((long)this.GetHashCode(), "{0}: The SMTP address was not found in the user AD object for this mailbox. Sender={1}.", this, sender);
                throw new ObjectNotFoundException(ServerStrings.ADUserNotFound);
            }
            SharingPolicy sharingPolicy = DirectoryHelper.ReadSharingPolicy(mailboxOwner.MailboxInfo.MailboxGuid, mailboxOwner.MailboxInfo.IsArchive, recipientSession);

            SharedFolderDataEncryption.Tracer.TraceDebug <SharedFolderDataEncryption, object>((long)this.GetHashCode(), "{0}: Sharing policy to be applied to this user: {1}", this, (sharingPolicy == null) ? "<null>" : sharingPolicy.Id);
            SharingPolicyAction sharingPolicyActions = SharedFolderDataEncryption.GetSharingPolicyActions(sharingDataType.StoreObjectType);

            SharedFolderDataRecipient[] externalIdentities = SharedFolderDataEncryption.GetExternalIdentities(externalUserCollection, recipients);
            List <InvalidRecipient>     list = new List <InvalidRecipient>();
            Dictionary <TokenTarget, List <SharedFolderDataRecipient> > dictionary = new Dictionary <TokenTarget, List <SharedFolderDataRecipient> >(externalIdentities.Length, SharedFolderDataEncryption.TokenTargetComparer);

            for (int i = 0; i < recipients.Length; i++)
            {
                SharedFolderDataRecipient item2          = externalIdentities[i];
                ValidRecipient            validRecipient = recipients[i];
                SmtpAddress smtpAddress = new SmtpAddress(validRecipient.SmtpAddress);
                string      domain      = smtpAddress.Domain;
                if (sharingPolicy == null || !sharingPolicy.IsAllowedForAnySharing(domain, sharingPolicyActions))
                {
                    SharedFolderDataEncryption.Tracer.TraceDebug <string>((long)this.GetHashCode(), "Sharing policy does not allow user to share with domain {0}", domain);
                    list.Add(new InvalidRecipient(validRecipient.SmtpAddress, InvalidRecipientResponseCodeType.SystemPolicyBlocksSharingWithThisRecipient));
                }
                else
                {
                    SmtpAddress smtpAddress2 = new SmtpAddress(validRecipient.SmtpAddressForEncryption);
                    TokenTarget tokenTarget  = TargetUriResolver.Resolve(smtpAddress2.Domain, aduser.OrganizationId);
                    if (tokenTarget == null)
                    {
                        list.Add(new InvalidRecipient(validRecipient.SmtpAddress, InvalidRecipientResponseCodeType.RecipientOrganizationNotFederated));
                    }
                    else
                    {
                        List <SharedFolderDataRecipient> list2;
                        if (!dictionary.TryGetValue(tokenTarget, out list2))
                        {
                            list2 = new List <SharedFolderDataRecipient>(1);
                            dictionary.Add(tokenTarget, list2);
                        }
                        list2.Add(item2);
                    }
                }
            }
            List <EncryptedSharedFolderData> list3 = new List <EncryptedSharedFolderData>(dictionary.Count);
            SharedFolderData sharedFolderData      = new SharedFolderData();

            sharedFolderData.DataType          = sharingDataType.ExternalName;
            sharedFolderData.FolderId          = folderId;
            sharedFolderData.SharingUrl        = this.GetSharingUrl(aduser, frontEndLocator);
            sharedFolderData.FederationUri     = this.externalAuthentication.TokenValidator.TargetUri.ToString();
            sharedFolderData.SenderSmtpAddress = sender;
            DelegationTokenRequest delegationTokenRequest = new DelegationTokenRequest
            {
                FederatedIdentity = aduser.GetFederatedIdentity(),
                EmailAddress      = aduser.GetFederatedSmtpAddress(new SmtpAddress(sender)).ToString(),
                Offer             = Offer.SharingInviteMessage
            };
            SecurityTokenService securityTokenService = this.externalAuthentication.GetSecurityTokenService(aduser.OrganizationId);

            foreach (KeyValuePair <TokenTarget, List <SharedFolderDataRecipient> > keyValuePair in dictionary)
            {
                delegationTokenRequest.Target = keyValuePair.Key;
                sharedFolderData.Recipients   = keyValuePair.Value.ToArray();
                try
                {
                    RequestedToken requestedToken = securityTokenService.IssueToken(delegationTokenRequest);
                    list3.Add(this.Encrypt(requestedToken, sharedFolderData));
                }
                catch (WSTrustException ex)
                {
                    foreach (SharedFolderDataRecipient sharedFolderDataRecipient in sharedFolderData.Recipients)
                    {
                        list.Add(new InvalidRecipient(sharedFolderDataRecipient.SmtpAddress, SharedFolderDataEncryption.GetResponseCodeFromException(ex), ex.ToString()));
                    }
                }
            }
            return(new EncryptionResults(list3.ToArray(), list.ToArray()));
        }
Exemplo n.º 9
0
        private void Process()
        {
            base.WriteObject(Environment.NewLine + Environment.NewLine + "Begin process.");
            base.WriteObject(Environment.NewLine + "STEP 1 of 6: Getting ADUser information for " + this.UserIdentity.ToString() + "...");
            ADUser user = this.GetUser();

            if (user == null)
            {
                LocalizedException exception = new LocalizedException(new LocalizedString("Error: tried to initialized user, but this.GetUser() returned null when called in Process()"));
                base.ThrowTerminatingError(exception, ErrorCategory.InvalidData, null);
            }
            base.WriteObject("RESULT: Success.");
            ADSessionSettings adsessionSettings = ADSessionSettings.FromOrganizationIdWithoutRbacScopes(ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest(), user.OrganizationId, null, false);

            adsessionSettings.IsSharedConfigChecked = true;
            IConfigurationSession tenantOrTopologyConfigurationSession = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(this.DomainController, true, ConsistencyMode.IgnoreInvalid, adsessionSettings, 201, "Process", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\Federation\\TestFederationTrust.cs");

            tenantOrTopologyConfigurationSession.GetFederatedOrganizationId(user.OrganizationId);
            base.WriteObject(Environment.NewLine + "STEP 2 of 6: Getting FederationTrust object for " + this.UserIdentity.ToString() + "...");
            FederationTrust federationTrust = this.GetFederationTrust(user);

            if (federationTrust == null)
            {
                LocalizedException exception2 = new LocalizedException(new LocalizedString("Error: tried to initialized federationTrust, but this.GetFederationTrust(user) returned null when called in Process()"));
                base.ThrowTerminatingError(exception2, ErrorCategory.InvalidData, null);
            }
            base.WriteObject("RESULT: Success.");
            base.WriteObject(Environment.NewLine + "STEP 3 of 6: Validating that the FederationTrust has the same STS certificates as the actual certificates published by the STS in the federation metadata.");
            this.ValidateFederationTrustCertificatesWithFederationMetadata(federationTrust);
            base.WriteObject("RESULT: Success.");
            base.WriteObject(Environment.NewLine + "STEP 4 of 6: Getting STS and Organization certificates from the federation trust object...");
            X509Certificate2[] stsCertificates          = this.GetStsCertificates(federationTrust);
            X509Certificate2[] organizationCertificates = this.GetOrganizationCertificates(federationTrust);
            if (stsCertificates == null)
            {
                LocalizedException exception3 = new LocalizedException(new LocalizedString("Error: GetStsCertificates(federationTrust) returned null when called in Process()"));
                base.ThrowTerminatingError(exception3, ErrorCategory.InvalidData, null);
            }
            if (organizationCertificates == null)
            {
                LocalizedException exception4 = new LocalizedException(new LocalizedString("Error: GetOrganizationCertificates(federationTrust) returned null when called in Process()"));
                base.ThrowTerminatingError(exception4, ErrorCategory.InvalidData, null);
            }
            base.WriteObject("RESULT: Success." + Environment.NewLine + " ");
            SecurityTokenService securityTokenService = new SecurityTokenService(federationTrust.TokenIssuerEpr, LiveConfiguration.GetWebProxy(new WriteVerboseDelegate(base.WriteVerbose)), organizationCertificates[0], federationTrust.TokenIssuerUri, federationTrust.PolicyReferenceUri, federationTrust.ApplicationUri.OriginalString);

            this.PrintConfiguration(user, federationTrust);
            base.WriteObject(Environment.NewLine + "STEP 5 of 6: Requesting delegation token...");
            RequestedToken delegationToken = this.GetDelegationToken(user, federationTrust.ApplicationUri, securityTokenService);

            base.WriteObject("RESULT: Success. Token retrieved.");
            if (delegationToken != null)
            {
                base.WriteObject(Environment.NewLine + "STEP 6 of 6: Validating delegation token...");
                TokenValidator tokenValidator = new TokenValidator(federationTrust.ApplicationUri, stsCertificates, organizationCertificates);
                this.ValidateToken(delegationToken, tokenValidator);
                base.WriteObject("RESULT: Success.");
            }
            else
            {
                LocalizedException exception5 = new LocalizedException(new LocalizedString("Error. Attempted to get delegation token, but token came back as null."));
                base.ThrowTerminatingError(exception5, ErrorCategory.InvalidData, null);
            }
            base.WriteVerbose(new LocalizedString(Environment.NewLine + "COMPLETE." + Environment.NewLine));
        }