Esempio n. 1
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);
        }
 public override void BeginInvoke(TaskCompleteCallback callback)
 {
     base.BeginInvoke(callback);
     this.stopwatch = Stopwatch.StartNew();
     try
     {
         DelegationTokenRequest request = new DelegationTokenRequest
         {
             FederatedIdentity = this.user.GetFederatedIdentity(),
             EmailAddress      = this.GetFederatedSmtpAddress().ToString(),
             Target            = this.target,
             Offer             = this.offer
         };
         this.asyncResult = this.securityTokenService.BeginIssueToken(request, new AsyncCallback(this.Complete), null);
     }
     catch (LocalizedException ex)
     {
         this.exception = ex;
         base.Complete();
     }
 }
 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 void Discover(ExchangePrincipal principal, ADUser executingUser, out string ewsEndpoint, out DelegationTokenRequest ewsTokenRequest)
        {
            SmtpAddress              value           = principal.MailboxInfo.RemoteIdentity.Value;
            ADSessionSettings        sessionSettings = ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(OrganizationId.ForestWideOrgId);
            IRecipientSession        tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.FullyConsistent, null, sessionSettings, ConfigScopes.TenantSubTree, 168, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs");
            ADUser                   aduser = null;
            TransportConfigContainer transportConfigContainer = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(true, ConsistencyMode.IgnoreInvalid, sessionSettings, 171, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs").FindSingletonConfigurationObject <TransportConfigContainer>();

            if (transportConfigContainer != null && transportConfigContainer.OrganizationFederatedMailbox != SmtpAddress.NullReversePath)
            {
                SmtpAddress  organizationFederatedMailbox = transportConfigContainer.OrganizationFederatedMailbox;
                ProxyAddress proxyAddress = null;
                try
                {
                    proxyAddress = ProxyAddress.Parse(organizationFederatedMailbox.ToString());
                }
                catch (ArgumentException ex)
                {
                    ExTraceGlobals.SessionTracer.TraceError <string>((long)this.GetHashCode(), "Proxy address of organization federated mailbox is invalid: {0}", ex.ToString());
                }
                if (proxyAddress != null && !(proxyAddress is InvalidProxyAddress))
                {
                    aduser = (tenantOrRootOrgRecipientSession.FindByProxyAddress(proxyAddress) as ADUser);
                }
            }
            OrganizationIdCacheValue organizationIdCacheValue = OrganizationIdCache.Singleton.Get(OrganizationId.ForestWideOrgId);
            OrganizationRelationship organizationRelationship = organizationIdCacheValue.GetOrganizationRelationship(value.Domain);

            if (aduser == null || organizationRelationship == null)
            {
                throw new OrganizationNotFederatedException();
            }
            DelegationTokenRequest request = new DelegationTokenRequest
            {
                FederatedIdentity = aduser.GetFederatedIdentity(),
                EmailAddress      = aduser.GetFederatedSmtpAddress().ToString(),
                Target            = organizationRelationship.GetTokenTarget(),
                Offer             = Offer.Autodiscover
            };
            FedOrgCredentials credentials = new FedOrgCredentials(request, this.GetSecurityTokenService(aduser.OrganizationId));
            Uri uri = null;

            using (AutoDiscoverUserSettingsClient autoDiscoverUserSettingsClient = AutoDiscoverUserSettingsClient.CreateInstance(DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, sessionSettings, 215, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs"), credentials, value, organizationRelationship.TargetAutodiscoverEpr, MailboxSearchEwsClient.AutoDiscoverRequestedSettings))
            {
                UserSettings  userSettings  = autoDiscoverUserSettingsClient.Discover();
                StringSetting stringSetting = userSettings.GetSetting("ExternalEwsUrl") as StringSetting;
                if (stringSetting == null || !Uri.TryCreate(stringSetting.Value, UriKind.Absolute, out uri))
                {
                    throw new AutoDAccessException(ServerStrings.AutoDRequestFailed);
                }
            }
            ewsEndpoint = EwsWsSecurityUrl.Fix(uri.ToString());
            string text = null;

            if (executingUser.EmailAddresses != null && executingUser.EmailAddresses.Count > 0)
            {
                List <string> federatedEmailAddresses = executingUser.GetFederatedEmailAddresses();
                if (federatedEmailAddresses != null && federatedEmailAddresses.Count > 0)
                {
                    text = federatedEmailAddresses[0];
                }
            }
            if (string.IsNullOrEmpty(text))
            {
                ewsTokenRequest = new DelegationTokenRequest
                {
                    FederatedIdentity = aduser.GetFederatedIdentity(),
                    EmailAddress      = aduser.GetFederatedSmtpAddress().ToString(),
                    Target            = organizationRelationship.GetTokenTarget(),
                    Offer             = Offer.MailboxSearch
                };
                return;
            }
            ewsTokenRequest = new DelegationTokenRequest
            {
                FederatedIdentity = executingUser.GetFederatedIdentity(),
                EmailAddress      = text.ToString(),
                Target            = organizationRelationship.GetTokenTarget(),
                Offer             = Offer.MailboxSearch
            };
        }
Esempio n. 5
0
        private SoapHttpClientAuthenticator CreateAuthenticator(Offer offer)
        {
            DelegationTokenRequest delegationTokenRequest = this.GetDelegationTokenRequest(offer);

            SharingEngine.Tracer.TraceDebug <DelegationTokenRequest>((long)this.GetHashCode(), "Requesting token for: {0}", delegationTokenRequest);
            if (this.adUser == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "adUser is null here");
                throw new ADUserNotFoundException();
            }
            if (this.externalAuthentication == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "externalAuthentication is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("externalAuthentication"));
            }
            SecurityTokenService securityTokenService = this.externalAuthentication.GetSecurityTokenService(this.adUser.OrganizationId);

            if (securityTokenService == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "securityTokenService is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("securityTokenService"));
            }
            Stopwatch      stopwatch = Stopwatch.StartNew();
            bool           flag      = false;
            RequestedToken requestedToken;

            try
            {
                requestedToken = securityTokenService.IssueToken(delegationTokenRequest);
                flag           = true;
            }
            catch (WSTrustException ex)
            {
                SharingEngine.Tracer.TraceError <WSTrustException>((long)this.GetHashCode(), "Unable to request token due exception: {0}", ex);
                throw new FailedCommunicationException(ex, delegationTokenRequest);
            }
            finally
            {
                if (flag)
                {
                    stopwatch.Stop();
                    PerformanceCounters.AverageExternalAuthenticationTokenRequestTime.IncrementBy(stopwatch.ElapsedTicks);
                    PerformanceCounters.AverageExternalAuthenticationTokenRequestTimeBase.Increment();
                    PerformanceCounters.SuccessfulExternalAuthenticationTokenRequests.Increment();
                }
                else
                {
                    PerformanceCounters.FailedExternalAuthenticationTokenRequests.Increment();
                }
            }
            if (requestedToken == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "token is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("token"));
            }
            if (this.subscription == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "subscription is null here");
                throw new SubscriptionNotFoundException();
            }
            XmlElement any = SharingKeyHandler.Encrypt(new SmtpAddress(this.subscription.SharingKey), requestedToken.ProofToken);
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(requestedToken);

            soapHttpClientAuthenticator.AdditionalSoapHeaders.Add(new SharingSecurityHeader(any));
            return(soapHttpClientAuthenticator);
        }
Esempio n. 6
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()));
        }
Esempio n. 7
0
        protected virtual bool TryGetExchangeRpcUrlFromAutodiscoverSettings(SmtpAddress remoteIdentity, SecurityTokenService securityTokenService, DelegationTokenRequest autoDiscoveryTokenRequest, Uri autoDiscoveryEndpoint, out Uri exchangeRpcUrl)
        {
            exchangeRpcUrl = null;
            FedOrgCredentials credentials = new FedOrgCredentials(autoDiscoveryTokenRequest, securityTokenService);
            bool result;

            using (AutoDiscoverUserSettingsClient autoDiscoverUserSettingsClient = AutoDiscoverUserSettingsClient.CreateInstance(DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, this.storeSession.MailboxOwner.MailboxInfo.OrganizationId.ToADSessionSettings(), 250, "TryGetExchangeRpcUrlFromAutodiscoverSettings", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\ExchangePrincipal\\RemoteMailboxProperties.cs"), credentials, remoteIdentity, autoDiscoveryEndpoint, RemoteMailboxProperties.AutodiscoveryRequestedSettings))
            {
                autoDiscoverUserSettingsClient.AnchorMailbox = this.storeSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString();
                UserSettings  userSettings  = autoDiscoverUserSettingsClient.Discover();
                StringSetting stringSetting = userSettings.GetSetting(RemoteMailboxProperties.AutodiscoveryRequestedSettings[0]) as StringSetting;
                result = (stringSetting != null && Uri.TryCreate(stringSetting.Value, UriKind.Absolute, out exchangeRpcUrl));
            }
            return(result);
        }
 internal FailedCommunicationException(Exception innerException, DelegationTokenRequest delegationTokenRequest) : base(Strings.FailedCommunicationException, innerException)
 {
     this.Data.Add("Delegation Token Request", delegationTokenRequest);
 }