Exemple #1
0
        // Token: 0x06000310 RID: 784 RVA: 0x000132E8 File Offset: 0x000114E8
        private static RfriContext CreateRfriContext(ClientBinding clientBinding)
        {
            RfriContext rfriContext = null;

            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                ClientSecurityContext clientSecurityContext = null;
                bool   isAnonymous = false;
                string text        = null;
                string userDomain  = null;
                RpcHttpConnectionProperties rpcHttpConnectionProperties = null;
                if (!RpcDispatch.TryGetAuthContextInfo(clientBinding, out clientSecurityContext, out isAnonymous, out text, out userDomain, out rpcHttpConnectionProperties))
                {
                    ExTraceGlobals.ReferralTracer.TraceError <Guid>(0L, "Could not resolve anonymous user for session id: {0}", clientBinding.AssociationGuid);
                    throw new RfriException(RfriStatus.LogonFailed, "Could not resolve anonymous user.");
                }
                disposeGuard.Add <ClientSecurityContext>(clientSecurityContext);
                Guid empty = Guid.Empty;
                if (rpcHttpConnectionProperties != null && rpcHttpConnectionProperties.RequestIds.Length > 0)
                {
                    Guid.TryParse(rpcHttpConnectionProperties.RequestIds[rpcHttpConnectionProperties.RequestIds.Length - 1], out empty);
                }
                rfriContext = new RfriContext(clientSecurityContext, userDomain, clientBinding.ClientAddress, clientBinding.ServerAddress, clientBinding.ProtocolSequence, clientBinding.AuthenticationType.ToString(), clientBinding.IsEncrypted, isAnonymous, empty);
                disposeGuard.Add <RfriContext>(rfriContext);
                if (!rfriContext.TryAcquireBudget())
                {
                    ExTraceGlobals.ReferralTracer.TraceError((long)rfriContext.ContextHandle, "Could not acquire budget");
                    throw new RfriException(RfriStatus.GeneralFailure, "Failed to acquire budget.");
                }
                disposeGuard.Success();
            }
            return(rfriContext);
        }
Exemple #2
0
        /// <summary>
        /// Bind SWN to the RPC server.
        /// </summary>
        /// <param name="serverName">SWN server name to bind</param>
        /// <param name="bindCred">Credential to bind SWN server</param>
        /// <param name="secContext">Security provider for RPC</param>
        /// <param name="timeout">Timeout for bind and requests</param>
        /// <param name="authLevel">RPCE authentication level</param>
        /// <returns>Return true if success, or false for fail</returns>
        ///<exception cref="ArgumentNullException">
        /// Thrown when serverName is null or empty.
        /// </exception>
        public bool SwnBind(
            string serverName,
            AccountCredential bindCred,
            ClientSecurityContext secContext,
            RpceAuthenticationLevel authLevel,
            TimeSpan timeout)
        {
            if (string.IsNullOrEmpty(serverName))
            {
                throw new ArgumentNullException("serverName");
            }

            //Query endpoint on SWN server
            ushort[] endpoints = SwnUtility.QueryEndpoints(serverName);

            bool retVal = RpcBind(
                RpceUtility.RPC_OVER_TCPIP_PROTOCOL_SEQUENCE,
                serverName,
                endpoints[0].ToString(),
                bindCred,
                secContext,
                authLevel,
                timeout);

            rpceTimeout = timeout;

            return(retVal);
        }
Exemple #3
0
        private static FreeBusyPermissionLevel FromInternalClient(InternalClientContext internalClientContext, RawSecurityDescriptor securityDescriptor, FreeBusyQuery freeBusyQuery)
        {
            if (internalClientContext.ClientSecurityContext == null)
            {
                FreeBusyPermission.SecurityTracer.TraceDebug <object, EmailAddress>(0L, "{0}: Caller {1} has no ClientSecurityContext, using default context as 'everyone'.", TraceContext.Get(), freeBusyQuery.Email);
                return(FreeBusyPermission.AccessCheck(securityDescriptor, ClientSecurityContext.FreeBusyPermissionDefaultClientSecurityContext));
            }
            if (!Configuration.UseDisabledAccount || VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).Global.MultiTenancy.Enabled)
            {
                return(FreeBusyPermission.GetPermissionLevel(internalClientContext.ClientSecurityContext, freeBusyQuery, securityDescriptor));
            }
            FreeBusyPermission.SecurityTracer.TraceDebug <object, InternalClientContext>(0L, "{0}: Creating a munged security context for caller {1}.", TraceContext.Get(), internalClientContext);
            ClientSecurityContext clientSecurityContext = null;

            try
            {
                clientSecurityContext = new SlaveAccountTokenMunger().MungeToken(internalClientContext.ClientSecurityContext, OrganizationId.ForestWideOrgId);
                return(FreeBusyPermission.GetPermissionLevel(clientSecurityContext, freeBusyQuery, securityDescriptor));
            }
            catch (TokenMungingException arg)
            {
                FreeBusyPermission.SecurityTracer.TraceError <object, InternalClientContext, TokenMungingException>(0L, "{0}: Unable to get the munged token for Caller {1}, error {2}, using the client context supplied.", TraceContext.Get(), internalClientContext, arg);
            }
            finally
            {
                if (clientSecurityContext != null)
                {
                    clientSecurityContext.Dispose();
                }
            }
            return(FreeBusyPermission.GetPermissionLevel(internalClientContext.ClientSecurityContext, freeBusyQuery, securityDescriptor));
        }
        internal IAsyncResult BeginGetMailTipsInBatches(RecipientInfo[] recipientsInfo, RecipientInfo senderInfo, bool doesNeedConfig, AsyncCallback asyncCallback, object asyncCallbackData)
        {
            this.primarySmtpAddress = this.userContext.ExchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString();
            ClientSecurityContext clientSecurityContext = this.userContext.LogonIdentity.ClientSecurityContext.Clone();
            string         weekdayDateTimeFormat        = this.userContext.UserOptions.GetWeekdayDateTimeFormat(true);
            MailTipsState  mailTipsState  = new MailTipsState(recipientsInfo, senderInfo, doesNeedConfig, this.userContext.ExchangePrincipal.LegacyDn, this.primarySmtpAddress, clientSecurityContext, this.userContext.TimeZone, this.userContext.UserCulture, this.userContext.ExchangePrincipal.MailboxInfo.OrganizationId, this.userContext.MailboxIdentity.GetOWAMiniRecipient().QueryBaseDN, this.userContext.UserOptions.HideMailTipsByDefault, this.userContext.PendingRequestManager, Query <IEnumerable <MailTips> > .GetCurrentHttpRequestServerName(), weekdayDateTimeFormat);
            OwaAsyncResult owaAsyncResult = new OwaAsyncResult(asyncCallback, asyncCallbackData);

            Interlocked.Increment(ref this.concurrentRequestCount);
            if (3 >= this.concurrentRequestCount)
            {
                ExTraceGlobals.CoreCallTracer.TraceError <int, string>((long)this.GetHashCode(), "MailTipsNotificationHandler.BeginGetMailTipsInBatches, serving concurrent request {0} for {1}", this.concurrentRequestCount, this.primarySmtpAddress);
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.GetMailTipsWorker), mailTipsState);
                return(owaAsyncResult);
            }
            IAsyncResult result;

            try
            {
                ExTraceGlobals.CoreCallTracer.TraceError <int>((long)this.GetHashCode(), "MailTipsNotificationHandler.BeginGetMailTipsInBatches, maximum concurrent request limit {0} has been reached", 3);
                MailTipsNotificationHandler.PopulateException(mailTipsState, new OwaMaxConcurrentRequestsExceededException("Maximum MailTips concurrent requests exceeded"), this.GetHashCode());
                this.mailTipsNotifier.AddToPayload(mailTipsState);
                this.mailTipsNotifier.PickupData();
                result = owaAsyncResult;
            }
            finally
            {
                Interlocked.Decrement(ref this.concurrentRequestCount);
            }
            return(result);
        }
        private static OwaClientSecurityContextIdentity InternalCreateFromClientSecurityContextIdentity(ClientSecurityContextIdentity cscIdentity, string logonName, OrganizationId userOrganizationId = null)
        {
            SidBasedIdentity sidBasedIdentity = cscIdentity as SidBasedIdentity;

            if (sidBasedIdentity != null)
            {
                OwaClientSecurityContextIdentity.PrePopulateUserGroupSids(sidBasedIdentity);
            }
            OwaClientSecurityContextIdentity result;

            try
            {
                using (ClientSecurityContext clientSecurityContext = cscIdentity.CreateClientSecurityContext())
                {
                    result = new OwaClientSecurityContextIdentity(clientSecurityContext, logonName, cscIdentity.AuthenticationType, userOrganizationId);
                }
            }
            catch (AuthzException ex)
            {
                ExTraceGlobals.CoreTracer.TraceDebug <string, string, AuthzException>(0L, "OwaClientSecurityContextIdentity.CreateFromClientSecurityContextIdentity for ClientSecurityContextIdentity.Name={0} ClientSecurityContextIdentity.AuthenticationType={1} failed with exception: {2}", cscIdentity.Name, cscIdentity.AuthenticationType, ex);
                if (ex.InnerException is Win32Exception)
                {
                    throw new OwaIdentityException("There was a problem creating the Client Security Context.", ex);
                }
                throw;
            }
            return(result);
        }
Exemple #6
0
 protected XsoMailboxDataProviderBase(ExchangePrincipal mailboxOwner, ISecurityAccessToken userToken, string action)
 {
     using (DisposeGuard disposeGuard = this.Guard())
     {
         Util.ThrowOnNullArgument(mailboxOwner, "mailboxOwner");
         Util.ThrowOnNullOrEmptyArgument(action, "action");
         if (userToken == null)
         {
             this.MailboxSession = MailboxSession.Open(mailboxOwner, new WindowsPrincipal(WindowsIdentity.GetCurrent()), CultureInfo.InvariantCulture, string.Format("Client=Management;Action={0}", action));
         }
         else
         {
             try
             {
                 using (ClientSecurityContext clientSecurityContext = new ClientSecurityContext(userToken, AuthzFlags.AuthzSkipTokenGroups))
                 {
                     clientSecurityContext.SetSecurityAccessToken(userToken);
                     this.MailboxSession = MailboxSession.Open(mailboxOwner, clientSecurityContext, CultureInfo.InvariantCulture, string.Format("Client=Management;Action={0}", action));
                 }
             }
             catch (AuthzException ex)
             {
                 throw new AccessDeniedException(new LocalizedString(ex.Message));
             }
         }
         disposeGuard.Success();
     }
 }
Exemple #7
0
        internal static MailboxSession OpenMailboxSessionAsOwner(ExchangePrincipal principal, ISecurityAccessToken userToken, string taskName)
        {
            TaskLogger.LogEnter();
            MailboxSession result = null;

            if (principal == null)
            {
                throw new ArgumentNullException("principal");
            }
            if (string.IsNullOrEmpty(taskName))
            {
                throw new ArgumentNullException("taskName");
            }
            if (userToken == null)
            {
                result = MailboxSession.Open(principal, new WindowsPrincipal(WindowsIdentity.GetCurrent()), CultureInfo.InvariantCulture, string.Format("Client=Management;Action={0}", taskName));
            }
            else
            {
                try
                {
                    using (ClientSecurityContext clientSecurityContext = new ClientSecurityContext(userToken, AuthzFlags.AuthzSkipTokenGroups))
                    {
                        clientSecurityContext.SetSecurityAccessToken(userToken);
                        result = MailboxSession.Open(principal, clientSecurityContext, CultureInfo.InvariantCulture, string.Format("Client=Management;Action={0}", taskName));
                    }
                }
                catch (AuthzException ex)
                {
                    throw new AccessDeniedException(new LocalizedString(ex.Message));
                }
            }
            TaskLogger.LogExit();
            return(result);
        }
        public DrsrClientSessionContext BindOverTcp(
            string serverName,
            ClientSecurityContext securityContext,
            RpceAuthenticationLevel authenticationLevel,
            TimeSpan timeout)
        {
            DrsrClientSessionContext clientSessionContext = new DrsrClientSessionContext();

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

            this.rpcAdapter.Bind(
                RpceUtility.RPC_OVER_TCPIP_PROTOCOL_SEQUENCE,
                serverName,
                DrsrUtility.QueryDrsrTcpEndpoint(DrsrRpcInterfaceType.DSAOP, serverName)[0].ToString(),
                securityContext,
                authenticationLevel,
                timeout);

            clientSessionContext.RPCHandle = rpcAdapter.Handle;

            return(clientSessionContext);
        }
        /// <summary>
        /// Connects to the vSphere service using SSPI.
        /// </summary>
        /// <returns>The client authentication <see cref="SspiToken" />.</returns>
        public SspiToken ConnectUsingSspi()
        {
            PrepareToConnect();

            LogDebug($"Connecting to vSphere using SSPI.");
            using (ClientSecurityCredential clientCredential = new ClientSecurityCredential(SecurityPackage.Negotiate))
            {
                using (ClientSecurityContext clientContext = new ClientSecurityContext(clientCredential, null, SecurityContextAttributes.None))
                {
                    SspiToken clientToken = clientContext.Initialize();

                    try
                    {
                        // Attempt to login with the client token.  This will result in an SSPIChallenge fault the first time.
                        _vimService.LoginBySSPI(_serviceContent.sessionManager, clientToken.TokenString, null);
                    }
                    catch (SoapException ex)
                    {
                        // The SOAP exception will contain a token from the server which can be used to re-initalize the client context.
                        // After initialization, login again using the client token.
                        clientToken = clientContext.Initialize(new SspiToken(ex.Detail.InnerText));
                        _vimService.LoginBySSPI(_serviceContent.sessionManager, clientToken.TokenString, null);
                    }
                    return(clientToken);
                }
            }
        }
        private void InnerBind(
            string protocolSequence,
            string networkAddress,
            string endpoint,
            AccountCredential transportCredential,
            ClientSecurityContext securityContext)
        {
            if (RpceClientTransport != null)
            {
                throw new InvalidOperationException("SRVS has already been bind");
            }

            RpceClientTransport = new RpceClientTransport();

            try
            {
                RpceClientTransport.Bind(
                    protocolSequence,
                    networkAddress,
                    endpoint,
                    transportCredential,
                    SrvsUtility.SRVS_INTERFACE_UUID,
                    SrvsUtility.SRVS_INTERFACE_MAJOR_VERSION,
                    SrvsUtility.SRVS_INTERFACE_MINOR_VERSION,
                    securityContext,
                    AuthenticationLevel,
                    true,
                    RpceTimeout);
            }
            catch
            {
                RpceClientTransport = null;
                throw;
            }
        }
        public static OwaClientSecurityContextIdentity CreateFromLiveIDIdentity(LiveIDIdentity liveIDIdentity)
        {
            if (liveIDIdentity == null)
            {
                throw new ArgumentNullException("liveIDIdentity");
            }
            OwaLiveIDIdentity owaLiveIDIdentity = new OwaLiveIDIdentity(liveIDIdentity.Sid, liveIDIdentity.HasAcceptedAccruals);

            owaLiveIDIdentity.userOrganizationProperties = liveIDIdentity.UserOrganizationProperties;
            owaLiveIDIdentity.DomainName = SmtpAddress.Parse(liveIDIdentity.MemberName).Domain;
            try
            {
                ClientSecurityContext clientSecurityContext = liveIDIdentity.CreateClientSecurityContext();
                owaLiveIDIdentity.UpgradePartialIdentity(clientSecurityContext, liveIDIdentity.PrincipalName, string.Empty);
            }
            catch (AuthzException ex)
            {
                if (ex.InnerException is Win32Exception)
                {
                    OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_ErrorCreatingClientContext, string.Empty, new object[]
                    {
                        owaLiveIDIdentity.UserSid.ToString(),
                        ex.ToString()
                    });
                    throw new OwaCreateClientSecurityContextFailedException("There was a problem creating the Client Security Context.");
                }
                throw;
            }
            return(owaLiveIDIdentity);
        }
Exemple #12
0
        internal InternalClientContext(ClientSecurityContext clientSecurityContext, IBudget budget, ExTimeZone timeZone, CultureInfo clientCulture, string messageId, ADUser adUser) : base(budget, timeZone, clientCulture, messageId)
        {
            if (clientSecurityContext == null)
            {
                throw new ArgumentNullException("clientSecurityContext");
            }
            this.clientSecurityContext     = clientSecurityContext;
            this.ownsClientSecurityContext = false;
            if (adUser != null)
            {
                this.adUser            = adUser;
                this.organizationId    = adUser.OrganizationId;
                this.adUserInitialized = true;
            }
            else
            {
                this.adUser            = null;
                this.adUserInitialized = false;
            }
            if (this.clientSecurityContext.UserSid != null)
            {
                this.identityForFilteredTracing = this.clientSecurityContext.UserSid.ToString();
            }
            SecurityAccessToken securityAccessToken = new SecurityAccessToken();

            this.clientSecurityContext.SetSecurityAccessToken(securityAccessToken);
            this.serializedSecurityContext = new SerializedSecurityContext(securityAccessToken);
        }
        /// <summary>
        /// Bind to DRSR RPC server.
        /// </summary>
        /// <param name="protocolSequence">
        /// RPC protocol sequence.
        /// </param>
        /// <param name="networkAddress">
        /// RPC network address.
        /// </param>
        /// <param name="endpoint">
        /// RPC endpoint.
        /// </param>
        /// <param name="securityContext">
        /// RPC security provider.
        /// </param>
        /// <param name="authenticationLevel">
        /// RPC authentication level.
        /// </param>
        /// <param name="timeout">
        /// Timeout
        /// </param>
        public void Bind(
            string protocolSequence,
            string networkAddress,
            string endpoint,
            ClientSecurityContext securityContext,
            RpceAuthenticationLevel authenticationLevel,
            TimeSpan timeout)
        {
            if (rpceClientTransport != null)
            {
                throw new InvalidOperationException("DRSR has already been bind.");
            }

            rpceTimeout = timeout;

            rpceClientTransport = new RpceClientTransport();

            rpceClientTransport.Bind(
                protocolSequence,
                networkAddress,
                endpoint,
                null,
                DrsrUtility.DSAOP_RPC_INTERFACE_UUID,
                DrsrUtility.DSAOP_RPC_INTERFACE_MAJOR_VERSION,
                DrsrUtility.DSAOP_RPC_INTERFACE_MINOR_VERSION,
                securityContext,
                authenticationLevel,
                false,
                rpceTimeout);
        }
Exemple #14
0
        // Token: 0x06000313 RID: 787 RVA: 0x0001366C File Offset: 0x0001186C
        private ICancelableAsyncResult BeginWrapper(string methodName, CancelableAsyncCallback asyncCallback, object asyncState, ClientBinding clientBinding, string legacyDn, Func <RfriContext, RfriDispatchTask> beginDelegate)
        {
            ICancelableAsyncResult asyncResult = null;

            RfriAsyncDispatch.ConditionalExceptionWrapper(ExTraceGlobals.ReferralTracer.IsTraceEnabled(TraceType.DebugTrace), delegate
            {
                if (ExTraceGlobals.ReferralTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    using (ClientSecurityContext clientSecurityContext = clientBinding.GetClientSecurityContext())
                    {
                        ExTraceGlobals.ReferralTracer.TraceDebug(0, 0L, "{0} started. LegacyDn={1}. ClientAddress={2}. ServerAddress={3}. ProtocolSequence={4}. EndPoint={5}. IsEncrypted={6}. ClientSecurityContext={7}.", new object[]
                        {
                            methodName,
                            legacyDn,
                            clientBinding.ClientAddress,
                            clientBinding.ServerAddress,
                            clientBinding.ProtocolSequence,
                            clientBinding.ClientEndpoint,
                            clientBinding.IsEncrypted,
                            clientSecurityContext
                        });
                    }
                }
                FailureAsyncResult <RfriStatus> failureAsyncResult = null;
                this.CheckShuttingDown();
                try
                {
                    using (DisposeGuard disposeGuard = default(DisposeGuard))
                    {
                        RfriContext rfriContext = RfriAsyncDispatch.CreateRfriContext(clientBinding);
                        disposeGuard.Add <RfriContext>(rfriContext);
                        RfriDispatchTask rfriDispatchTask = beginDelegate(rfriContext);
                        disposeGuard.Add <RfriDispatchTask>(rfriDispatchTask);
                        asyncResult = rfriDispatchTask.AsyncResult;
                        this.SubmitTask(rfriDispatchTask);
                        disposeGuard.Success();
                    }
                }
                catch (FailRpcException ex)
                {
                    failureAsyncResult = new FailureAsyncResult <RfriStatus>((RfriStatus)ex.ErrorCode, IntPtr.Zero, ex, asyncCallback, asyncState);
                    asyncResult        = failureAsyncResult;
                }
                catch (RfriException ex2)
                {
                    failureAsyncResult = new FailureAsyncResult <RfriStatus>(ex2.Status, IntPtr.Zero, ex2, asyncCallback, asyncState);
                    asyncResult        = failureAsyncResult;
                }
                if (failureAsyncResult != null && !ThreadPool.QueueUserWorkItem(RfriAsyncDispatch.FailureWaitCallback, failureAsyncResult))
                {
                    failureAsyncResult.InvokeCallback();
                }
                ExTraceGlobals.ReferralTracer.TraceDebug <string>(0, 0L, "{0} succeeded.", methodName);
            }, delegate(Exception exception)
            {
                ExTraceGlobals.ReferralTracer.TraceDebug <string, Exception>(0, 0L, "{0} failed. Exception={1}.", methodName, exception);
            });
            return(asyncResult);
        }
        private static bool CanPostItemsToPublicFolder(Folder publicFolder, ClientSecurityContext userContext)
        {
            RawSecurityDescriptor rawSecurityDescriptor = publicFolder.TryGetProperty(FolderSchema.SecurityDescriptor) as RawSecurityDescriptor;
            int grantedAccess = userContext.GetGrantedAccess(rawSecurityDescriptor, AccessMask.DeleteChild);

            MailPublicFolderPermissionHandler.Diag.TraceDebug <int, Folder>(0L, "Granted access {0} for user on public folder {1}", grantedAccess, publicFolder);
            return((grantedAccess & 2) != 0);
        }
Exemple #16
0
 // Token: 0x060004BA RID: 1210 RVA: 0x0001D3F7 File Offset: 0x0001B5F7
 private ClientSecurityContextWrapper(ClientSecurityContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     this.clientSecurityContext = context;
     this.AddRef();
 }
Exemple #17
0
 private static FreeBusyPermissionLevel GetPermissionLevel(ClientSecurityContext clientSecurityContext, FreeBusyQuery freeBusyQuery, RawSecurityDescriptor securityDescriptor)
 {
     if (FreeBusyPermission.CallerHasFullPermission(clientSecurityContext, freeBusyQuery))
     {
         FreeBusyPermission.SecurityTracer.TraceDebug <object, ClientSecurityContext, EmailAddress>(0L, "{0}: Caller {1} has owner access on mailbox {2}.", TraceContext.Get(), clientSecurityContext, freeBusyQuery.Email);
         return(FreeBusyPermissionLevel.Owner);
     }
     return(FreeBusyPermission.AccessCheck(securityDescriptor, clientSecurityContext));
 }
 private void Initialize(ClientSecurityContext context, AuthzContextHandle handle, ClientIdentityInfo clientIdentityInfo, string userDn, IADOrgPerson adEntry, GenericIdentity auxiliaryIdentity)
 {
     this.context            = context;
     this.authzContextHandle = handle;
     this.clientIdentityInfo = clientIdentityInfo;
     this.userDn             = userDn;
     this.adEntry            = adEntry;
     this.auxiliaryIdentity  = auxiliaryIdentity;
 }
Exemple #19
0
        private void SwitchToNTLMSSP(byte[] securityToken)
        {
            securityMechContext         = null; // try use NTLM
            this.client.Config.MechList = new MechTypeList(new MechType[] { this.client.Config.MechList.Elements[1] });
            InitializeSecurityContext(this.client.Config.MechList.Elements[0], null);
            //this.client.Context.NegotiationState = SpngNegotiationState.AcceptIncomplete;
            securityMechContext.Initialize(securityToken);

            UpdateNegotiationToken(securityToken);
        }
        // Token: 0x06001056 RID: 4182 RVA: 0x0004F320 File Offset: 0x0004D520
        private AddressBookBase GetGlobalAddressList(OrganizationId organizationId)
        {
            AddressBookBase globalAddressList;

            using (ClientSecurityContext clientSecurityContext = new ClientSecurityContext(this.securityAccessToken, AuthzFlags.AuthzSkipTokenGroups))
            {
                ADSessionSettings sessionSettings = ADSessionSettings.FromOrganizationIdWithoutRbacScopes(ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest(), organizationId, null, false);
                globalAddressList = AddressBookBase.GetGlobalAddressList(clientSecurityContext, DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, sessionSettings, 512, "GetGlobalAddressList", "f:\\15.00.1497\\sources\\dev\\data\\src\\directory\\RbacScope.cs"), DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.IgnoreInvalid, null, sessionSettings, ConfigScopes.TenantSubTree, 513, "GetGlobalAddressList", "f:\\15.00.1497\\sources\\dev\\data\\src\\directory\\RbacScope.cs"), true);
            }
            return(globalAddressList);
        }
Exemple #21
0
 private InternalClientContext(InternalClientContext clientContext, ClientSecurityContext clientSecurityContext, bool ownsClientSecurityContext, ExchangeVersionType requestSchemaVersion) : base(clientContext.Budget, clientContext.TimeZone, clientContext.ClientCulture, clientContext.MessageId)
 {
     this.clientSecurityContext     = clientSecurityContext;
     this.ownsClientSecurityContext = ownsClientSecurityContext;
     this.adUser                     = clientContext.adUser;
     this.adUserInitialized          = clientContext.adUserInitialized;
     this.organizationId             = clientContext.OrganizationId;
     this.serializedSecurityContext  = clientContext.serializedSecurityContext;
     this.identityForFilteredTracing = clientContext.identityForFilteredTracing;
     this.RequestSchemaVersion       = requestSchemaVersion;
 }
Exemple #22
0
 internal static void AddGroupMailboxAccessSid(ClientSecurityContext clientSecurityContext, Guid groupMailboxGuid, UnifiedGroupMemberType memberType)
 {
     ArgumentValidator.ThrowIfInvalidValue <UnifiedGroupMemberType>("memberType", memberType, (UnifiedGroupMemberType x) => memberType != UnifiedGroupMemberType.Unknown || memberType != UnifiedGroupMemberType.None);
     SecurityIdentity.GroupMailboxMemberType groupMailboxMemberType = (memberType == UnifiedGroupMemberType.Member) ? SecurityIdentity.GroupMailboxMemberType.Member : SecurityIdentity.GroupMailboxMemberType.Owner;
     if (!clientSecurityContext.AddGroupSids(GroupMailboxAuthorizationHandler.GetGroupMailboxSidBinaryAndAttributes(groupMailboxGuid, groupMailboxMemberType)))
     {
         GroupMailboxAuthorizationHandler.Tracer.TraceError <SecurityIdentifier, Guid, uint>(0L, "GroupMailboxAccess: Unable to add well known group sid to user {0} for the mailbox = {1}...Error = {2}", clientSecurityContext.UserSid, groupMailboxGuid, NativeMethods.GetLastError());
         return;
     }
     GroupMailboxAuthorizationHandler.Tracer.TraceDebug <SecurityIdentifier, Guid>(0L, "GroupMailboxAccess: Successfully munged the token of the user {0} for the mailbox = {1}", clientSecurityContext.UserSid, groupMailboxGuid);
 }
Exemple #23
0
        /// <summary>
        /// Release all resources
        /// </summary>
        /// <param name="disposing">Indicate user or GC calling this method</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    securityMechContext = null;
                }

                disposed = true;
            }
        }
 // Token: 0x06000D5D RID: 3421 RVA: 0x00059578 File Offset: 0x00057778
 internal void UpgradePartialIdentity(ClientSecurityContext clientSecurityContext, string logonName, string authenticationType)
 {
     this.clientSecurityContext = clientSecurityContext;
     this.logonName             = logonName;
     this.authenticationType    = authenticationType;
     if (this.clientSecurityContext.UserSid != this.userSid)
     {
         throw new OwaInvalidOperationException("Can't upgrade a partial identity to a full identity that doesn't correspond to the same user sid");
     }
     this.userSid          = null;
     this.owaMiniRecipient = null;
 }
Exemple #25
0
 public CallerInfo(bool isOpenAsAdmin, CommonAccessToken commonAccessToken, ClientSecurityContext securityContext, string primarySmtpAddress, OrganizationId orgId, string userAgent, Guid queryCorrelationId, string[] userRoles, string[] applicationRoles)
 {
     this.isOpenAsAdmin         = isOpenAsAdmin;
     this.commonAccessToken     = commonAccessToken;
     this.clientSecurityContext = securityContext;
     this.orgId = orgId;
     this.primarySmtpAddress = primarySmtpAddress;
     this.userAgent          = userAgent;
     this.queryCorrelationId = queryCorrelationId;
     this.userRoles          = userRoles;
     this.applicationRoles   = applicationRoles;
 }
Exemple #26
0
        internal static NspiContext CreateContext(ClientBinding clientBinding)
        {
            NspiContext result;

            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                ClientSecurityContext clientSecurityContext = null;
                bool   isAnonymous = false;
                string text        = null;
                string userDomain  = null;
                RpcHttpConnectionProperties rpcHttpConnectionProperties = null;
                if (!RpcDispatch.TryGetAuthContextInfo(clientBinding, out clientSecurityContext, out isAnonymous, out text, out userDomain, out rpcHttpConnectionProperties))
                {
                    ExTraceGlobals.NspiTracer.TraceError <Guid>(0L, "Could not resolve anonymous user for session id: {0}", clientBinding.AssociationGuid);
                    throw new NspiException(NspiStatus.LogonFailed, "Could not resolve anonymous user.");
                }
                disposeGuard.Add <ClientSecurityContext>(clientSecurityContext);
                Guid empty = Guid.Empty;
                if (rpcHttpConnectionProperties != null && rpcHttpConnectionProperties.RequestIds.Length > 0)
                {
                    Guid.TryParse(rpcHttpConnectionProperties.RequestIds[rpcHttpConnectionProperties.RequestIds.Length - 1], out empty);
                }
                NspiContext nspiContext = new NspiContext(clientSecurityContext, userDomain, clientBinding.ClientAddress, clientBinding.ServerAddress, clientBinding.ProtocolSequence, empty);
                disposeGuard.Add <NspiContext>(nspiContext);
                nspiContext.IsAnonymous = isAnonymous;
                if (!nspiContext.TryAcquireBudget())
                {
                    ExTraceGlobals.NspiTracer.TraceError((long)nspiContext.ContextHandle, "Could not acquire budget");
                    throw new NspiException(NspiStatus.GeneralFailure, "Failed to acquire budget.");
                }
                bool flag = false;
                lock (ClientContextCache.clientContextDictionaryLock)
                {
                    flag = ClientContextCache.clientContextDictionary.ContainsKey(nspiContext.ContextHandle);
                    if (!flag)
                    {
                        ClientContextCache.clientContextDictionary.Add(nspiContext.ContextHandle, nspiContext);
                        AddressBookPerformanceCountersWrapper.AddressBookPerformanceCounters.NspiConnectionsCurrent.RawValue = (long)ClientContextCache.clientContextDictionary.Count;
                        AddressBookPerformanceCountersWrapper.AddressBookPerformanceCounters.NspiConnectionsTotal.Increment();
                        AddressBookPerformanceCountersWrapper.AddressBookPerformanceCounters.NspiConnectionsRate.Increment();
                    }
                }
                if (flag)
                {
                    ExTraceGlobals.NspiTracer.TraceError((long)nspiContext.ContextHandle, "Duplicate contextHandle found in context dictionary");
                    throw new NspiException(NspiStatus.GeneralFailure, "Duplicate contextHandle found in context dictionary.");
                }
                disposeGuard.Success();
                result = nspiContext;
            }
            return(result);
        }
Exemple #27
0
        /// <summary>
        /// Initialize the securityMechContext based on the security package type
        /// </summary>
        /// <param name="mechType">security mechanism type</param>
        /// <param name="inToken">the input security token</param>
        /// <exception cref="InvalidOperationException">Thrown if could not find the configuration.</exception>
        /// <exception cref="InvalidOperationException">Thrown when security configuration is unknown</exception>
        private void InitializeSecurityContext(MechType mechType, byte[] inToken)
        {
            SpngClientContext   clientContext = this.client.Context as SpngClientContext;
            SecurityPackageType authType      = SpngUtility.ConvertMechType(mechType);

            CurrentSecurityConfig = SpngUtility.GetSecurityConfig(this.securityConfigList, authType);

            if (CurrentSecurityConfig == null)
            {
                throw new InvalidOperationException("Missing configuration for " + authType.ToString());
            }

            if (securityMechContext != null)
            {
                // re-enter. Nothing need to do
                return;
            }

            if (CurrentSecurityConfig.GetType() == typeof(KerberosClientSecurityConfig))
            {
                KerberosClientSecurityConfig kileConfig = CurrentSecurityConfig as KerberosClientSecurityConfig;

                securityMechContext = new KerberosClientSecurityContext(
                    kileConfig.ServiceName,
                    kileConfig.ClientCredential,
                    KerberosAccountType.User,
                    kileConfig.KdcIpAddress,
                    kileConfig.KdcPort,
                    kileConfig.TransportType,
                    kileConfig.SecurityAttributes);
            }
            else if (CurrentSecurityConfig.GetType() == typeof(NlmpClientSecurityConfig))
            {
                NlmpClientSecurityConfig nlmpConfig = CurrentSecurityConfig as NlmpClientSecurityConfig;

                NlmpClientCredential cred = new NlmpClientCredential(
                    nlmpConfig.TargetName,
                    nlmpConfig.DomainName,
                    nlmpConfig.AccountName,
                    nlmpConfig.Password);
                securityMechContext = new NlmpClientSecurityContext(cred, nlmpConfig.SecurityAttributes);
            }
            else if (CurrentSecurityConfig.GetType() == typeof(SspiClientSecurityConfig))
            {
                throw new InvalidOperationException("Only support Kerberos security config and NTLM security config");
            }
            else
            {
                throw new InvalidOperationException("unknown security config");
            }
        }
Exemple #28
0
        private static ClientSecurityContext TryMungeTokenFromSlaveAccount(ClientSecurityContext account)
        {
            ClientSecurityContext result;

            try
            {
                result = new SlaveAccountTokenMunger().MungeToken(account, OrganizationId.ForestWideOrgId);
            }
            catch (TokenMungingException)
            {
                result = null;
            }
            return(result);
        }
 private OwaClientSecurityContextIdentity(ClientSecurityContext clientSecurityContext, string logonName, string authenticationType, OrganizationId userOrganizationId)
 {
     if (clientSecurityContext == null)
     {
         throw new ArgumentNullException("clientSecurityContext");
     }
     if (string.IsNullOrEmpty(logonName))
     {
         throw new ArgumentNullException("logonName", "logonName cannot be null or empty.");
     }
     if (userOrganizationId == null && !OwaIdentity.IsLogonNameFullyQualified(logonName))
     {
         throw new ArgumentException("logonName", string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid logon name.", new object[]
         {
             logonName
         }));
     }
     if (string.IsNullOrEmpty(authenticationType))
     {
         throw new ArgumentNullException("authenticationType", "authenticationType cannot be null or empty.");
     }
     this.logonName          = logonName;
     this.authenticationType = authenticationType;
     base.UserOrganizationId = userOrganizationId;
     if (!SyncUtilities.IsDatacenterMode())
     {
         this.clientSecurityContext = clientSecurityContext;
         OWAMiniRecipient owaminiRecipient = base.GetOWAMiniRecipient();
         if (owaminiRecipient != null && owaminiRecipient.MasterAccountSid != null)
         {
             try
             {
                 this.clientSecurityContext = OwaClientSecurityContextIdentity.TokenMunger.MungeToken(clientSecurityContext, OrganizationId.ForestWideOrgId);
                 return;
             }
             catch (TokenMungingException ex)
             {
                 ExTraceGlobals.CoreCallTracer.TraceError(0L, "OwaClientSecurityContextIdentity.TokenMunger.MungeToken for LogonName='{0}', AuthenticationType='{1}', UserOrgId='{2}' failed with exception: {3}", new object[]
                 {
                     this.logonName,
                     this.authenticationType,
                     base.UserOrganizationId,
                     ex.Message
                 });
             }
         }
     }
     this.clientSecurityContext = clientSecurityContext.Clone();
 }
Exemple #30
0
        private static UserContextKey GetUserContextKey(HttpContext httpContext, ClientSecurityContext overrideClientSecurityContext, out UserContextCookie userContextCookie)
        {
            UserContextKey userContextKey    = null;
            string         explicitLogonUser = UserContextUtilities.GetExplicitLogonUser(httpContext);

            if (string.IsNullOrEmpty(explicitLogonUser))
            {
                userContextCookie = UserContextCookie.GetUserContextCookie(httpContext);
                if (userContextCookie != null)
                {
                    ExTraceGlobals.UserContextCallTracer.TraceDebug <UserContextCookie>(0L, "Found cookie in the request: {0}", userContextCookie);
                    if (overrideClientSecurityContext == null)
                    {
                        userContextKey = UserContextKey.CreateFromCookie(userContextCookie, httpContext);
                    }
                    else
                    {
                        userContextKey = UserContextKey.CreateFromCookie(userContextCookie, overrideClientSecurityContext.UserSid);
                    }
                }
            }
            else
            {
                userContextCookie = null;
                if (UserContextManager.RequestRequiresSharedContext(httpContext))
                {
                    userContextKey = UserContextKey.Create("D894745CADD64DB9B00309200288E1E7", "SharedAdmin", explicitLogonUser);
                }
                else
                {
                    SecurityIdentifier securityIdentifier = httpContext.User.Identity.GetSecurityIdentifier();
                    if (securityIdentifier == null)
                    {
                        ExTraceGlobals.UserContextCallTracer.TraceDebug <IIdentity>(0L, "UserContextManager.GetUserContextKey: current user has no security identifier - '{0}'", httpContext.User.Identity);
                        ExWatson.SendReport(new InvalidOperationException(string.Format("UserContextManager.GetUserContextKey: current user has no security identifier - '{0}'", httpContext.User.Identity)), ReportOptions.None, null);
                        return(null);
                    }
                    string logonUniqueKey = securityIdentifier.ToString();
                    string text           = httpContext.Request.Headers["X-OWA-Test-ExplicitLogonUserId"];
                    if (string.IsNullOrEmpty(text) || !AppConfigLoader.GetConfigBoolValue("Test_OwaAllowHeaderOverride", false))
                    {
                        text = "B387FD19C8C4416694EB79909BED70B5";
                    }
                    userContextKey = UserContextKey.Create(text, logonUniqueKey, explicitLogonUser);
                    ExTraceGlobals.UserContextCallTracer.TraceDebug <UserContextKey>(0L, "Cookie not found but this is explicit logon. Generated Key: {0}", userContextKey);
                }
            }
            return(userContextKey);
        }