private Uri Discover()
        {
            string sharerIdentity = this.subscription.SharerIdentity;
            Uri    result;

            using (AutodiscoverClient autodiscoverClient = new AutodiscoverClient())
            {
                autodiscoverClient.RequestedServerVersion = DefaultBinding_Autodiscover.Exchange2010RequestedServerVersion;
                autodiscoverClient.Authenticator          = this.CreateAuthenticator(Offer.Autodiscover);
                autodiscoverClient.Proxy     = this.WebProxy;
                autodiscoverClient.UserAgent = "ExchangeSharingSync";
                ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 1351, "Discover", "f:\\15.00.1497\\sources\\dev\\infoworker\\src\\common\\Sharing\\SharingEngine.cs");
                string[] autodiscoverTrustedHosters = topologyConfigurationSession.GetAutodiscoverTrustedHosters();
                if (autodiscoverTrustedHosters != null)
                {
                    autodiscoverClient.AllowedHostnames.AddRange(autodiscoverTrustedHosters);
                }
                UserSettings userSettings = SharingEngine.SingleGetUserSettings.Discover(autodiscoverClient, sharerIdentity);
                if (userSettings.IsSettingError("ExternalEwsUrl"))
                {
                    SharingEngine.Tracer.TraceError <UserSettings>((long)this.GetHashCode(), "ExternalEwsUrl not present in response: {0}", userSettings);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                UserSetting setting = userSettings.GetSetting("ExternalEwsUrl");
                if (setting == null)
                {
                    SharingEngine.Tracer.TraceError <UserSettings>((long)this.GetHashCode(), "ExternalEwsUrl not present in response: {0}", userSettings);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                StringSetting stringSetting = setting as StringSetting;
                if (stringSetting == null)
                {
                    SharingEngine.Tracer.TraceError <Type>((long)this.GetHashCode(), "Unexpected type for ExternalEwsUrl in response. Type is {0}", setting.GetType());
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                if (string.IsNullOrEmpty(stringSetting.Value))
                {
                    SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "Empty value returned for ExternalEwsUrl in response.");
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                if (!Uri.IsWellFormedUriString(stringSetting.Value, UriKind.Absolute))
                {
                    SharingEngine.Tracer.TraceError <string>((long)this.GetHashCode(), "Value returned for ExternalEwsUrl is not well-formed URL: {0}", stringSetting.Value);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                Uri uri = new Uri(EwsWsSecurityUrl.Fix(stringSetting.Value));
                if (uri.Scheme != Uri.UriSchemeHttps)
                {
                    SharingEngine.Tracer.TraceError <string>((long)this.GetHashCode(), "Response has non-HTTPS ExternalEwsUrl: {0}", stringSetting.Value);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                SharingEngine.Tracer.TraceDebug <Uri>((long)this.GetHashCode(), "Received valid response: {0}", uri);
                result = uri;
            }
            return(result);
        }
 public void Authenticate(CustomSoapHttpClientProtocol client)
 {
     ProxyAuthenticator.SecurityTracer.TraceDebug <object, AuthenticatorType>((long)this.GetHashCode(), "{0}: Authenticating client with {1}", TraceContext.Get(), this.AuthenticatorType);
     client.Authenticator = this.authenticator;
     if (this.AuthenticatorType == AuthenticatorType.WSSecurity)
     {
         client.Url = EwsWsSecurityUrl.Fix(client.Url);
         client.ConnectionGroupName = "WS>";
         return;
     }
     client.Url = EwsWsSecurityUrl.FixForAnonymous(client.Url);
     client.UnsafeAuthenticatedConnectionSharing = Configuration.UnsafeAuthenticatedConnectionSharing.Value;
     client.ConnectionGroupName = "NC>";
 }
Beispiel #3
0
        protected AutoDiscoverRequestResult GetAutodiscoverResult(string urlValue, string versionValue, EmailAddress emailAddress)
        {
            if (string.IsNullOrEmpty(urlValue) || !Uri.IsWellFormedUriString(urlValue, UriKind.Absolute))
            {
                SoapAutoDiscoverRequest.AutoDiscoverTracer.TraceError((long)this.GetHashCode(), "{0}: Request '{1}' got ExternalEwsUrl setting for user {2} has invalid value: {3}", new object[]
                {
                    TraceContext.Get(),
                    this,
                    emailAddress.Address,
                    urlValue
                });
                return(null);
            }
            int serverVersion = Globals.E14Version;

            if (!string.IsNullOrEmpty(versionValue))
            {
                Exception ex = null;
                try
                {
                    Version version = new Version(versionValue);
                    serverVersion = version.ToInt();
                }
                catch (ArgumentException ex2)
                {
                    ex = ex2;
                }
                catch (FormatException ex3)
                {
                    ex = ex3;
                }
                catch (OverflowException ex4)
                {
                    ex = ex4;
                }
                if (ex != null)
                {
                    SoapAutoDiscoverRequest.AutoDiscoverTracer.TraceError <object, Exception>((long)this.GetHashCode(), "{0}: Exception parsing version: {1}", TraceContext.Get(), ex);
                }
            }
            string url = urlValue;

            if (this.authenticator.ProxyAuthenticator != null && this.authenticator.ProxyAuthenticator.AuthenticatorType == AuthenticatorType.WSSecurity)
            {
                url = EwsWsSecurityUrl.Fix(url);
            }
            return(new AutoDiscoverRequestResult(this.TargetUri, null, null, new WebServiceUri(url, null, UriSource.EmailDomain, serverVersion), null, null));
        }
Beispiel #4
0
        private string GetEnterpriseOrE14SharingUrl(ExchangePrincipal exchangePrincipal)
        {
            SharedFolderDataEncryption.Tracer.TraceDebug <ExchangePrincipal, bool>((long)this.GetHashCode(), "Entering GetEnterpriseOrE14SharingUrl - mailbox {0}, isMultitenancyEnabled={1}", exchangePrincipal, this.IsMultitenancyEnabled);
            ServiceTopology            serviceTopology = this.IsMultitenancyEnabled ? ServiceTopology.GetCurrentLegacyServiceTopology("f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 655) : ServiceTopology.GetCurrentServiceTopology("f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 655);
            IList <WebServicesService> list            = serviceTopology.FindAll <WebServicesService>(exchangePrincipal, ClientAccessType.External, SharedFolderDataEncryption.serviceVersionFilter, "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 658);

            if (list.Count != 0)
            {
                return(EwsWsSecurityUrl.Fix(list[0].Url.ToString()));
            }
            SharedFolderDataEncryption.Tracer.TraceDebug <ExchangePrincipal>((long)this.GetHashCode(), "Unable to find a CAS with external access in same site of user {0}. Trying other sites.", exchangePrincipal);
            WebServicesService webServicesService = serviceTopology.FindAny <WebServicesService>(ClientAccessType.External, SharedFolderDataEncryption.serviceVersionFilter, "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 671);

            if (webServicesService == null)
            {
                throw new NoExternalEwsAvailableException();
            }
            return(EwsWsSecurityUrl.Fix(webServicesService.Url.ToString()));
        }
Beispiel #5
0
        private string GetE15MultitenancySharingUrl(ExchangePrincipal exchangePrincipal, IFrontEndLocator frontEndLocator)
        {
            SharedFolderDataEncryption.Tracer.TraceDebug <ExchangePrincipal>((long)this.GetHashCode(), "Entering GetE15MultitenancySharingUrl for mailbox {0}", exchangePrincipal);
            Uri       uri = null;
            Exception ex  = null;

            try
            {
                uri = frontEndLocator.GetWebServicesUrl(exchangePrincipal);
            }
            catch (ServerNotFoundException ex2)
            {
                ex = ex2;
            }
            catch (ADTransientException ex3)
            {
                ex = ex3;
            }
            catch (DataSourceOperationException ex4)
            {
                ex = ex4;
            }
            catch (DataValidationException ex5)
            {
                ex = ex5;
            }
            finally
            {
                if (ex != null)
                {
                    throw new NoExternalEwsAvailableException(ex);
                }
            }
            string text = uri.ToString();

            SharedFolderDataEncryption.Tracer.TraceDebug <string>((long)this.GetHashCode(), "GetE15MultitenancySharingUrl - EWS url '{0}'", text);
            string text2 = EwsWsSecurityUrl.Fix(text);

            SharedFolderDataEncryption.Tracer.TraceDebug <string>((long)this.GetHashCode(), "GetE15MultitenancySharingUrl - fixed EWS url '{0}'", text2);
            return(text2);
        }
        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
            };
        }
        public static AutoDiscoverUserSettingsClient CreateInstance(ITopologyConfigurationSession topologyConfigurationSession, FedOrgCredentials credentials, SmtpAddress identity, Uri autoDiscoveryEndpoint, string[] requestedSettings)
        {
            Util.ThrowOnNullArgument(credentials, "credentials");
            RequestedToken token;

            try
            {
                token = credentials.GetToken();
            }
            catch (WSTrustException ex)
            {
                string text  = identity.ToString();
                string text2 = ex.ToString();
                StorageGlobals.EventLogger.LogEvent(StorageEventLogConstants.Tuple_AutoDiscoverFailedToAquireSecurityToken, text, new object[]
                {
                    text,
                    text2
                });
                ExTraceGlobals.XtcTracer.TraceError <string, string>(0L, "AutoDiscover request failed for {0}, failed to aquire security token. Exception: {1}.", text, text2);
                throw new AutoDAccessException(ServerStrings.AutoDFailedToGetToken, ex);
            }
            return(new AutoDiscoverUserSettingsClient(topologyConfigurationSession, SoapHttpClientAuthenticator.Create(token), EwsWsSecurityUrl.Fix(autoDiscoveryEndpoint), identity, requestedSettings));
        }
Beispiel #8
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            base.InternalProcessRecord();
            ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 66, "InternalProcessRecord", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\Federation\\GetFederationInformation.cs");

            string[] autodiscoverTrustedHosters = topologyConfigurationSession.GetAutodiscoverTrustedHosters();
            using (AutodiscoverClient autodiscoverClient = new AutodiscoverClient())
            {
                Server localServer = LocalServerCache.LocalServer;
                if (localServer != null && localServer.InternetWebProxy != null)
                {
                    base.WriteVerbose(Strings.GetFederationInformationProxy(localServer.InternetWebProxy.ToString()));
                    autodiscoverClient.Proxy = new WebProxy(localServer.InternetWebProxy);
                }
                if (this.TrustedHostnames != null)
                {
                    autodiscoverClient.AllowedHostnames.AddRange(this.TrustedHostnames);
                }
                if (autodiscoverTrustedHosters != null)
                {
                    autodiscoverClient.AllowedHostnames.AddRange(autodiscoverTrustedHosters);
                }
                base.WriteVerbose(Strings.GetFederationInformationTrustedHostnames(autodiscoverClient.AllowedHostnames.ToString()));
                base.WriteProgress(Strings.GetFederationInformationProgress, Strings.DiscoveringDomain(this.DomainName.Domain), 5);
                List <GetFederationInformationResult> list = new List <GetFederationInformationResult>(GetFederationInformationClient.Discover(autodiscoverClient, this.DomainName.Domain));
                base.WriteProgress(Strings.GetFederationInformationProgress, Strings.DiscoveringDomain(this.DomainName.Domain), 25);
                base.WriteVerbose(Strings.GetFederationInformationResults(GetFederationInformation.GetFormattedResults(list)));
                GetFederationInformationResult result = this.GetResult(list);
                if (result == null)
                {
                    base.WriteError(new GetFederationInformationFailedException(list.ToArray()), (ErrorCategory)1001, null);
                }
                else
                {
                    ICollection domainNames;
                    if (this.BypassAdditionalDomainValidation)
                    {
                        domainNames = result.Domains;
                    }
                    else
                    {
                        domainNames = this.GetValidatedAdditionalDomains(autodiscoverClient, result.ApplicationUri, result.Domains);
                    }
                    if (result.TokenIssuerUris != null && result.TokenIssuerUris.Length > 0)
                    {
                        bool  flag  = false;
                        Uri[] array = Array.ConvertAll <string, Uri>(result.TokenIssuerUris, (string uri) => new Uri(uri, UriKind.RelativeOrAbsolute));
                        ExternalAuthentication current = ExternalAuthentication.GetCurrent();
                        if (current.Enabled)
                        {
                            foreach (SecurityTokenService securityTokenService in current.SecurityTokenServices)
                            {
                                Uri tokenIssuerUri = securityTokenService.TokenIssuerUri;
                                foreach (Uri uri2 in array)
                                {
                                    if (tokenIssuerUri.Equals(uri2))
                                    {
                                        base.WriteVerbose(Strings.GetFederationInformationTokenIssuerMatches(tokenIssuerUri.ToString(), uri2.ToString()));
                                        flag = true;
                                        break;
                                    }
                                    base.WriteVerbose(Strings.GetFederationInformationTokenIssuerDoesntMatch(tokenIssuerUri.ToString(), uri2.ToString()));
                                }
                            }
                            if (!flag)
                            {
                                StringBuilder stringBuilder = new StringBuilder(100);
                                foreach (SecurityTokenService securityTokenService2 in current.SecurityTokenServices)
                                {
                                    if (stringBuilder.Length > 0)
                                    {
                                        stringBuilder.Append(",");
                                    }
                                    stringBuilder.Append(securityTokenService2.TokenIssuerUri.ToString());
                                }
                                this.WriteWarning(Strings.GetFederationInformationTokenIssuerDoesntMatchAny(this.DomainName.ToString(), string.Join(",", result.TokenIssuerUris), stringBuilder.ToString()));
                            }
                        }
                    }
                    base.WriteObject(new FederationInformation(this.DomainName, new Uri(result.ApplicationUri, UriKind.RelativeOrAbsolute), result.TokenIssuerUris, domainNames, EwsWsSecurityUrl.Fix(result.Url)));
                }
                base.WriteProgress(Strings.GetFederationInformationProgress, Strings.ProgressStatusFinished, 100);
            }
            TaskLogger.LogExit();
        }