Пример #1
0
        private ExternalUser ApplyPermission(MailboxSession mailboxSession, SmtpAddress smtpAddress, SharingContext context)
        {
            ExternalUser externalUser = null;
            ExternalUser externalUser2;

            using (ExternalUserCollection externalUsers = mailboxSession.GetExternalUsers())
            {
                externalUser2 = externalUsers.FindReachUserWithOriginalSmtpAddress(smtpAddress);
                externalUser  = externalUsers.FindFederatedUserWithOriginalSmtpAddress(smtpAddress);
                if (externalUser2 == null)
                {
                    externalUser2 = externalUsers.AddReachUser(smtpAddress);
                    externalUsers.Save();
                }
            }
            using (FolderPermissionContext current = FolderPermissionContext.GetCurrent(mailboxSession, context))
            {
                FreeBusyAccess freeBusy = this.GetFreeBusy(context);
                PermissionSecurityPrincipal principal       = new PermissionSecurityPrincipal(externalUser2);
                PermissionLevel             permissionLevel = (context.SharingDetail == SharingContextDetailLevel.FullDetails) ? PermissionLevel.Reviewer : PermissionLevel.None;
                current.AddOrChangePermission(principal, permissionLevel, new FreeBusyAccess?(freeBusy));
                if (externalUser != null)
                {
                    current.RemovePermission(new PermissionSecurityPrincipal(externalUser));
                }
            }
            return(externalUser2);
        }
Пример #2
0
        public EncryptionResults Encrypt(IExchangePrincipal mailboxOwner, ExternalUserCollection externalUserCollection, string[] recipients, string sender, string containerClass, string folderId, IFrontEndLocator frontEndLocator, string domainController = null)
        {
            IRecipientSession session = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(domainController, true, ConsistencyMode.IgnoreInvalid, null, mailboxOwner.MailboxInfo.OrganizationId.ToADSessionSettings(), ConfigScopes.TenantSubTree, 121, "Encrypt", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs");

            ValidRecipient[] recipients2 = Array.ConvertAll <string, ValidRecipient>(recipients, (string recipient) => new ValidRecipient(recipient, session.FindByProxyAddress(new SmtpProxyAddress(recipient, false))));
            return(this.Encrypt(mailboxOwner, session, externalUserCollection, recipients2, sender, containerClass, folderId, frontEndLocator));
        }
        private ICollection <MapiAclTableRestriction.ExternalUserPermission> GetExternalUserPermissions(MapiAclTableAdapter mapiAclTableAdapter, IEnumerable <AclTableEntry.ModifyOperation> changingEntries)
        {
            List <MapiAclTableRestriction.ExternalUserPermission> list = null;
            ExternalUserCollection disposable = null;

            try
            {
                foreach (AclTableEntry.ModifyOperation modifyOperation in changingEntries)
                {
                    if (modifyOperation.Operation == ModifyTableOperationType.Add || modifyOperation.Operation == ModifyTableOperationType.Modify)
                    {
                        MapiAclTableRestriction.ExternalUserPermission externalUserPermission = this.TryGetExternalUserPermission(modifyOperation.Entry, mapiAclTableAdapter, ref disposable);
                        if (externalUserPermission != null)
                        {
                            if (list == null)
                            {
                                list = new List <MapiAclTableRestriction.ExternalUserPermission>();
                            }
                            list.Add(externalUserPermission);
                        }
                    }
                }
            }
            finally
            {
                Util.DisposeIfPresent(disposable);
            }
            return(list);
        }
 private static bool TryReadEntry(BinaryReader reader, out ExternalUser user)
 {
     if (reader.ReadUInt32() == ExternalUserCollection.ptagLocalDirectoryEntryId)
     {
         uint num = reader.ReadUInt32();
         MemoryPropertyBag memoryPropertyBag = new MemoryPropertyBag();
         int num2 = 0;
         while ((long)num2 < (long)((ulong)num))
         {
             uint   num3 = reader.ReadUInt32();
             object obj  = ExternalUserCollection.ReadPropValue(reader, ((PropTag)num3).ValueType(), reader.ReadUInt32());
             if (obj != null)
             {
                 PropertyTagPropertyDefinition prop = PropertyTagPropertyDefinition.CreateCustom(string.Empty, num3);
                 memoryPropertyBag.PreLoadStoreProperty(prop, obj, (int)num);
             }
             num2++;
         }
         memoryPropertyBag.SetAllPropertiesLoaded();
         IDirectPropertyBag directPropertyBag = memoryPropertyBag;
         if (directPropertyBag.IsLoaded(InternalSchema.MemberSIDLocalDirectory) && directPropertyBag.IsLoaded(InternalSchema.MemberExternalIdLocalDirectory) && directPropertyBag.IsLoaded(InternalSchema.MemberEmailLocalDirectory))
         {
             if (!directPropertyBag.IsLoaded(InternalSchema.MemberName))
             {
                 memoryPropertyBag[InternalSchema.MemberName] = directPropertyBag.GetValue(InternalSchema.MemberEmailLocalDirectory);
             }
             user = new ExternalUser(memoryPropertyBag);
             return(true);
         }
     }
     user = null;
     return(false);
 }
 private static object ReadPropValue(BinaryReader reader, PropType type, uint len)
 {
     if (type <= PropType.Binary)
     {
         if (type == PropType.Int)
         {
             return(ExternalUserCollection.ReadInt(reader, len));
         }
         if (type == PropType.String)
         {
             return(ExternalUserCollection.ReadString(reader, len));
         }
         if (type == PropType.Binary)
         {
             return(ExternalUserCollection.ReadBytes(reader, len));
         }
     }
     else
     {
         if (type == PropType.IntArray)
         {
             return(ExternalUserCollection.ReadArrayValue <int>(reader, len, new ExternalUserCollection.ReadValue <int>(ExternalUserCollection.ReadInt)));
         }
         if (type == PropType.StringArray)
         {
             return(ExternalUserCollection.ReadArrayValue <string>(reader, len, new ExternalUserCollection.ReadValue <string>(ExternalUserCollection.ReadString)));
         }
         if (type == PropType.BinaryArray)
         {
             return(ExternalUserCollection.ReadArrayValue <byte[]>(reader, len, new ExternalUserCollection.ReadValue <byte[]>(ExternalUserCollection.ReadBytes)));
         }
     }
     return(null);
 }
Пример #6
0
        private void LoadPublishedCalendarOptionsForReachUser()
        {
            this.publishedOptions = new MailboxCalendarFolder();
            PermissionSecurityPrincipal targetPrincipal = null;

            using (ExternalUserCollection externalUsers = base.MailboxSession.GetExternalUsers())
            {
                ExternalUser externalUser = externalUsers.FindExternalUser(this.reachUserSid);
                if (externalUser == null || !externalUser.IsReachUser)
                {
                    ExTraceGlobals.SharingTracer.TraceDebug <SecurityIdentifier, bool, bool>((long)this.GetHashCode(), "ReachAccessSid={0}, Found ExternalUser:{1}, IsReachUser:{2}", this.reachUserSid, externalUser != null, externalUser != null && externalUser.IsReachUser);
                    throw new PublishedFolderAccessDeniedException();
                }
                targetPrincipal = new PermissionSecurityPrincipal(externalUser);
            }
            DetailLevelEnumType?freeBusyAccessLevel = this.GetFreeBusyAccessLevel(targetPrincipal);

            if (freeBusyAccessLevel == null)
            {
                throw new PublishedFolderAccessDeniedException();
            }
            this.publishedOptions.DetailLevel          = freeBusyAccessLevel.Value;
            this.publishedOptions.PublishEnabled       = true;
            this.publishedOptions.PublishDateRangeFrom = DateRangeEnumType.OneMonth;
            this.publishedOptions.PublishDateRangeTo   = DateRangeEnumType.SixMonths;
        }
        private static string ReadString(BinaryReader reader, uint len)
        {
            string text  = new string(Encoding.Unicode.GetChars(ExternalUserCollection.ReadBytes(reader, len)));
            string text2 = text;

            char[] trimChars = new char[1];
            return(text2.TrimEnd(trimChars));
        }
        private ExternalUser InternalAdd(SmtpAddress smtpAddress, bool isReachUser)
        {
            this.CheckDisposed("InternalAdd");
            string       externalId   = ExternalUserCollection.CreateExternalIdentity(smtpAddress);
            ExternalUser externalUser = new ExternalUser(externalId, smtpAddress, isReachUser);

            this.Add(externalUser);
            return(externalUser);
        }
Пример #9
0
        internal static ExternalUser TryGetExternalUser(SecurityIdentifier sid, ExternalUserCollection externalUsers)
        {
            ExternalUser result = null;

            if (ExternalUser.IsExternalUserSid(sid) && externalUsers != null)
            {
                result = externalUsers.FindExternalUser(sid);
            }
            return(result);
        }
Пример #10
0
        private void AddNonADEntry(MapiAclTableAdapter mapiAclTableAdapter, ref ExternalUserCollection externalUsers, string memberName, long memberId, byte[] memberEntryId, MemberRights rights)
        {
            ExternalUser externalUser = mapiAclTableAdapter.TryGetExternalUser(memberEntryId, ref externalUsers);

            if (externalUser != null)
            {
                PermissionSecurityPrincipal securityPrincipal = new PermissionSecurityPrincipal(externalUser);
                Permission permission = this.permissionSet.CreatePermission(securityPrincipal, rights, memberId);
                this.AddPermissionEntry(securityPrincipal, permission);
                return;
            }
            ExTraceGlobals.StorageTracer.TraceDebug <string>(0L, "PermissionTable::PermissionTable. Member has invalid entry id, member name = {0}.", memberName);
            this.AddUnknownEntry(memberName, memberId, memberEntryId, rights);
        }
Пример #11
0
 protected override void InternalPerformRevocation(MailboxSession mailboxSession, SharingContext context)
 {
     using (FolderPermissionContext current = FolderPermissionContext.GetCurrent(mailboxSession, context))
     {
         using (ExternalUserCollection externalUsers = mailboxSession.GetExternalUsers())
         {
             PermissionSecurityPrincipal permissionSecurityPrincipal = this.CreatePermissionSecurityPrincipal(context.InitiatorSmtpAddress, externalUsers);
             if (permissionSecurityPrincipal != null)
             {
                 current.RemovePermission(permissionSecurityPrincipal);
             }
         }
     }
 }
        private static void WritePropValue(BinaryWriter writer, PropertyDefinition prop, MemoryPropertyBag propertyBag)
        {
            PropertyTagPropertyDefinition propertyTagPropertyDefinition = (PropertyTagPropertyDefinition)prop;

            writer.Write(propertyTagPropertyDefinition.PropertyTag);
            object   obj       = propertyBag.TryGetProperty(propertyTagPropertyDefinition);
            PropType propType  = ((PropTag)propertyTagPropertyDefinition.PropertyTag).ValueType();
            PropType propType2 = propType;

            if (propType2 <= PropType.Binary)
            {
                if (propType2 == PropType.Int)
                {
                    ExternalUserCollection.WriteIntValue(writer, (int)obj);
                    return;
                }
                if (propType2 == PropType.String)
                {
                    ExternalUserCollection.WriteStringValue(writer, (string)obj);
                    return;
                }
                if (propType2 == PropType.Binary)
                {
                    ExternalUserCollection.WriteByteValue(writer, (byte[])obj);
                    return;
                }
            }
            else
            {
                if (propType2 == PropType.IntArray)
                {
                    ExternalUserCollection.WriteArrayValue <int>(writer, (int[])obj, new ExternalUserCollection.WriteValue <int>(ExternalUserCollection.WriteIntValue));
                    return;
                }
                if (propType2 == PropType.StringArray)
                {
                    ExternalUserCollection.WriteArrayValue <string>(writer, (string[])obj, new ExternalUserCollection.WriteValue <string>(ExternalUserCollection.WriteStringValue));
                    return;
                }
                if (propType2 == PropType.BinaryArray)
                {
                    ExternalUserCollection.WriteArrayValue <byte[]>(writer, (byte[][])obj, new ExternalUserCollection.WriteValue <byte[]>(ExternalUserCollection.WriteByteValue));
                    return;
                }
            }
            writer.Write(0U);
        }
Пример #13
0
        private static SharedFolderDataRecipient GetExternalIdentity(ExternalUserCollection externalUserCollection, ValidRecipient recipient)
        {
            if (!SmtpAddress.IsValidSmtpAddress(recipient.SmtpAddress))
            {
                throw new ArgumentOutOfRangeException(ServerStrings.InvalidSmtpAddress(recipient.SmtpAddress));
            }
            SmtpAddress  smtpAddress  = new SmtpAddress(recipient.SmtpAddress);
            ExternalUser externalUser = externalUserCollection.FindFederatedUserWithOriginalSmtpAddress(smtpAddress);

            if (externalUser == null)
            {
                externalUser = externalUserCollection.AddFederatedUser(smtpAddress);
            }
            return(new SharedFolderDataRecipient
            {
                SmtpAddress = recipient.SmtpAddressForEncryption,
                SharingKey = externalUser.ExternalId.ToString()
            });
        }
        public SaveResult Save()
        {
            this.CheckDisposed("Save");
            if (!this.isDirty)
            {
                bool flag = false;
                foreach (ExternalUser externalUser in this.data)
                {
                    flag |= externalUser.PropertyBag.IsDirty;
                }
                if (!flag)
                {
                    return(SaveResult.Success);
                }
            }
            using (Stream stream = this.directoryMessage.OpenPropertyStream(InternalSchema.LocalDirectory, PropertyOpenMode.Create))
            {
                using (BinaryWriter binaryWriter = new BinaryWriter(stream))
                {
                    foreach (ExternalUser externalUser2 in this.data)
                    {
                        binaryWriter.Write(ExternalUserCollection.ptagLocalDirectoryEntryId);
                        ICollection <PropertyDefinition> allFoundProperties = externalUser2.PropertyBag.AllFoundProperties;
                        binaryWriter.Write((uint)allFoundProperties.Count);
                        ExternalUserCollection.WritePropValue(binaryWriter, InternalSchema.MemberSIDLocalDirectory, externalUser2.PropertyBag);
                        foreach (PropertyDefinition propertyDefinition in allFoundProperties)
                        {
                            if (propertyDefinition != InternalSchema.MemberSIDLocalDirectory)
                            {
                                ExternalUserCollection.WritePropValue(binaryWriter, propertyDefinition, externalUser2.PropertyBag);
                            }
                        }
                    }
                }
            }
            ConflictResolutionResult conflictResolutionResult = this.directoryMessage.Save(SaveMode.ResolveConflicts);

            return(conflictResolutionResult.SaveStatus);
        }
Пример #15
0
        public static byte[] BuildAclTableBlob(StoreSession session, RawSecurityDescriptor securityDescriptor, RawSecurityDescriptor freeBusySecurityDescriptor)
        {
            IRecipientSession      adrecipientSession = session.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid);
            ExternalUserCollection externalUserCollectionToDispose = null;
            bool   flag;
            string canonicalErrorInformation;
            List <AclTableEntry> source;

            try
            {
                source = AclModifyTable.BuildAclTableFromSecurityDescriptor(securityDescriptor, freeBusySecurityDescriptor, new LazilyInitialized <ExternalUserCollection>(delegate()
                {
                    MailboxSession mailboxSession   = session as MailboxSession;
                    externalUserCollectionToDispose = ((mailboxSession != null) ? mailboxSession.GetExternalUsers() : null);
                    return(externalUserCollectionToDispose);
                }), adrecipientSession, new AclTableIdMap(), out flag, out canonicalErrorInformation);
            }
            finally
            {
                Util.DisposeIfPresent(externalUserCollectionToDispose);
            }
            if (!flag)
            {
                ExTraceGlobals.StorageTracer.TraceError(0L, "Cannot build blob ACL table blob with non-canonical SD");
                throw new NonCanonicalACLException(canonicalErrorInformation);
            }
            FolderSecurity.AclTableAndSecurityDescriptorProperty aclTableAndSD = new FolderSecurity.AclTableAndSecurityDescriptorProperty(new ArraySegment <byte>(AclModifyTable.SerializeTableEntries(source)), source.ToDictionary((AclTableEntry tableEntry) => tableEntry.SecurityIdentifier, delegate(AclTableEntry tableEntry)
            {
                if (!tableEntry.IsGroup)
                {
                    return(FolderSecurity.SecurityIdentifierType.User);
                }
                return(FolderSecurity.SecurityIdentifierType.Group);
            }), SecurityDescriptor.FromRawSecurityDescriptor(securityDescriptor), SecurityDescriptor.FromRawSecurityDescriptor(freeBusySecurityDescriptor));
            return(AclModifyTable.SerializeAclTableAndSecurityDecscriptor(aclTableAndSD));
        }
        private MapiAclTableRestriction.ExternalUserPermission TryGetExternalUserPermission(AclTableEntry aclTableEntry, MapiAclTableAdapter mapiAclTableAdapter, ref ExternalUserCollection externalUsers)
        {
            Util.ThrowOnNullArgument(aclTableEntry, "aclTableEntry");
            Util.ThrowOnNullArgument(mapiAclTableAdapter, "mapiAclTableAdapter");
            MailboxSession mailboxSession = this.session as MailboxSession;

            if (mailboxSession == null)
            {
                return(null);
            }
            byte[]       memberEntryId = aclTableEntry.MemberEntryId;
            MemberRights memberRights  = aclTableEntry.MemberRights;
            long         memberId      = aclTableEntry.MemberId;

            if (memberEntryId == null || memberEntryId.Length == 0)
            {
                if (memberId <= 0L)
                {
                    return(null);
                }
                ExTraceGlobals.StorageTracer.TraceDebug <IExchangePrincipal, long>((long)this.GetHashCode(), "{0}: Getting memberEntryId from current ACL table for MemberId {1}.", mailboxSession.MailboxOwner, memberId);
                AclTableEntry byMemberId = mapiAclTableAdapter.GetByMemberId(memberId);
                if (byMemberId == null || byMemberId.MemberEntryId == null)
                {
                    ExTraceGlobals.StorageTracer.TraceDebug <IExchangePrincipal, long>((long)this.GetHashCode(), "{0}: Not found memberEntryId from current ACL table for MemberId {1}. Skipped.", mailboxSession.MailboxOwner, memberId);
                    return(null);
                }
                memberEntryId = byMemberId.MemberEntryId;
            }
            if (mapiAclTableAdapter.TryGetParticipantEntryId(memberEntryId) != null)
            {
                ExTraceGlobals.StorageTracer.TraceDebug <IExchangePrincipal>((long)this.GetHashCode(), "{0}: MemberEntryId indicates internal user. Skipped.", mailboxSession.MailboxOwner);
                return(null);
            }
            ExternalUser externalUser = mapiAclTableAdapter.TryGetExternalUser(memberEntryId, ref externalUsers);

            if (externalUser == null)
            {
                ExTraceGlobals.StorageTracer.TraceDebug <IExchangePrincipal>((long)this.GetHashCode(), "{0}: MemberEntryId is not external user. Skipped.", mailboxSession.MailboxOwner);
                return(null);
            }
            return(new MapiAclTableRestriction.ExternalUserPermission(externalUser, memberRights));
        }
Пример #17
0
        protected override PerformInvitationResults InternalPerformInvitation(MailboxSession mailboxSession, SharingContext context, ValidRecipient[] recipients, IFrontEndLocator frontEndLocator)
        {
            ExternalAuthentication current = ExternalAuthentication.GetCurrent();

            if (!current.Enabled)
            {
                ExTraceGlobals.SharingTracer.TraceError <string>((long)this.GetHashCode(), "{0}: The organization is not federated for external sharing.", context.InitiatorSmtpAddress);
                return(new PerformInvitationResults(new InvalidSharingRecipientsException(ValidRecipient.ConvertToStringArray(recipients), new OrganizationNotFederatedException())));
            }
            SharedFolderDataEncryption sharedFolderDataEncryption = new SharedFolderDataEncryption(current);
            string text = StoreId.StoreIdToEwsId(mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, context.FolderId);
            PerformInvitationResults result;

            using (ExternalUserCollection externalUsers = mailboxSession.GetExternalUsers())
            {
                PerformInvitationResults performInvitationResults = null;
                EncryptionResults        encryptionResults        = null;
                Exception ex = null;
                try
                {
                    encryptionResults = sharedFolderDataEncryption.Encrypt(mailboxSession.MailboxOwner, mailboxSession.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid), externalUsers, recipients, context.InitiatorSmtpAddress, context.FolderClass, text, frontEndLocator);
                }
                catch (UserWithoutFederatedProxyAddressException ex2)
                {
                    ex = ex2;
                }
                catch (InvalidFederatedOrganizationIdException ex3)
                {
                    ex = ex3;
                }
                catch (StoragePermanentException ex4)
                {
                    ex = ex4;
                }
                if (ex != null)
                {
                    ExTraceGlobals.SharingTracer.TraceError <string, Exception>((long)this.GetHashCode(), "{0}: Error occurred when trying to encrypt. Exception = {1}", context.InitiatorSmtpAddress, ex);
                    result = new PerformInvitationResults(new InvalidSharingRecipientsException(ValidRecipient.ConvertToStringArray(recipients), ex));
                }
                else
                {
                    if (encryptionResults.InvalidRecipients != null && encryptionResults.InvalidRecipients.Length > 0)
                    {
                        InvalidSharingRecipientsException exception = new InvalidSharingRecipientsException(encryptionResults.InvalidRecipients);
                        if (encryptionResults.InvalidRecipients.Length == recipients.Length)
                        {
                            return(new PerformInvitationResults(exception));
                        }
                        performInvitationResults = new PerformInvitationResults(recipients, exception);
                        recipients = performInvitationResults.SucceededRecipients;
                    }
                    else
                    {
                        performInvitationResults = new PerformInvitationResults(recipients);
                    }
                    PermissionLevel permissionLevel = this.GetPermissionLevel(context);
                    FreeBusyAccess? freeBusy        = this.GetFreeBusy(context);
                    using (FolderPermissionContext current2 = FolderPermissionContext.GetCurrent(mailboxSession, context))
                    {
                        foreach (ValidRecipient validRecipient in recipients)
                        {
                            PermissionSecurityPrincipal principal = this.CreatePermissionSecurityPrincipal(validRecipient.SmtpAddress, externalUsers);
                            current2.AddOrChangePermission(principal, permissionLevel, freeBusy);
                            ExternalUser externalUser = externalUsers.FindReachUserWithOriginalSmtpAddress(new SmtpAddress(validRecipient.SmtpAddress));
                            if (externalUser != null)
                            {
                                current2.RemovePermission(new PermissionSecurityPrincipal(externalUser));
                            }
                        }
                    }
                    context.FolderEwsId = text;
                    context.EncryptedSharedFolderDataCollection = encryptionResults.EncryptedSharedFolderDataCollection;
                    result = performInvitationResults;
                }
            }
            return(result);
        }
Пример #18
0
 public static bool TryGetUserFromEntryId(byte[] memberEntryId, StoreSession session, IRecipientSession recipientSession, ExternalUserCollection externalUsers, out string legacyDN, out SecurityIdentifier securityIdentifier, out List <SecurityIdentifier> sidHistory, out bool isGroup, out string displayName)
 {
     return(AclHelper.TryGetUserFromEntryId(memberEntryId, session, recipientSession, new LazilyInitialized <ExternalUserCollection>(() => externalUsers), out legacyDN, out securityIdentifier, out sidHistory, out isGroup, out displayName));
 }
Пример #19
0
        private void LoadFrom(MapiAclTableAdapter mapiAclTableAdapter)
        {
            IRecipientSession      recipientSession = null;
            ExternalUserCollection disposable       = null;

            AclTableEntry[] all = mapiAclTableAdapter.GetAll();
            try
            {
                foreach (AclTableEntry aclTableEntry in all)
                {
                    long         memberId      = aclTableEntry.MemberId;
                    byte[]       memberEntryId = aclTableEntry.MemberEntryId;
                    string       memberName    = aclTableEntry.MemberName;
                    MemberRights memberRights  = aclTableEntry.MemberRights;
                    if (memberId == 0L)
                    {
                        this.defaultMemberPermission = this.permissionSet.CreatePermission(new PermissionSecurityPrincipal(PermissionSecurityPrincipal.SpecialPrincipalType.Default), memberRights, memberId);
                    }
                    else if (memberId == -1L)
                    {
                        this.anonymousMemberPermission = this.permissionSet.CreatePermission(new PermissionSecurityPrincipal(PermissionSecurityPrincipal.SpecialPrincipalType.Anonymous), memberRights, memberId);
                    }
                    else if (memberEntryId != null)
                    {
                        ADParticipantEntryId adparticipantEntryId = mapiAclTableAdapter.TryGetParticipantEntryId(memberEntryId);
                        if (adparticipantEntryId != null)
                        {
                            if (recipientSession == null)
                            {
                                recipientSession = mapiAclTableAdapter.Session.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid);
                            }
                            ADRecipient adrecipient = null;
                            try
                            {
                                adrecipient = recipientSession.FindByLegacyExchangeDN(adparticipantEntryId.LegacyDN);
                            }
                            catch (DataValidationException)
                            {
                                ExTraceGlobals.StorageTracer.TraceDebug <string, string>(0L, "PermissionTable::PermissionTable. Caught exception from ADSesssion.FindByLegacyExchangeDN when trying to find a recipient from the ACL Table. Recipient name = {0}, LegDN = {1}.", memberName, adparticipantEntryId.LegacyDN);
                                this.AddUnknownEntry(memberName, memberId, memberEntryId, memberRights);
                                goto IL_17E;
                            }
                            if (adrecipient != null)
                            {
                                Permission permission = this.permissionSet.CreatePermission(new PermissionSecurityPrincipal(adrecipient), memberRights, memberId);
                                this.AddPermissionEntry(permission.Principal, permission);
                            }
                            else
                            {
                                ExTraceGlobals.StorageTracer.TraceDebug <string, string>(0L, "PermissionTable::PermissionTable. Did not find the recipient from the ACL table in the AD. Recipient name = {0}, LegDN = {1}.", memberName, adparticipantEntryId.LegacyDN);
                                this.AddUnknownEntry(memberName, memberId, memberEntryId, memberRights);
                            }
                        }
                        else
                        {
                            this.AddNonADEntry(mapiAclTableAdapter, ref disposable, memberName, memberId, memberEntryId, memberRights);
                        }
                    }
                    else
                    {
                        ExTraceGlobals.StorageTracer.TraceDebug <string>(0L, "PermissionTable::PermissionTable. Found a member in the ACL table (other than anonymous and default) without a member entry id. Recipient Name = {0}.", memberName);
                        this.AddUnknownEntry(memberName, memberId, memberEntryId, memberRights);
                    }
                    IL_17E :;
                }
            }
            finally
            {
                Util.DisposeIfPresent(disposable);
            }
        }
        internal ExternalUserCollection(MailboxSession session)
        {
            this.data = new List <ExternalUser>();
            byte[]       entryId      = null;
            StoreSession storeSession = null;
            bool         flag         = false;

            try
            {
                if (storeSession != null)
                {
                    storeSession.BeginMapiCall();
                    storeSession.BeginServerHealthCall();
                    flag = true;
                }
                if (StorageGlobals.MapiTestHookBeforeCall != null)
                {
                    StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                }
                entryId = session.Mailbox.MapiStore.GetLocalDirectoryEntryId();
            }
            catch (MapiPermanentException ex)
            {
                throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotLookupEntryId, ex, storeSession, this, "{0}. MapiException = {1}.", new object[]
                {
                    string.Format("Unable to lookup Local Directory EntryID", new object[0]),
                    ex
                });
            }
            catch (MapiRetryableException ex2)
            {
                throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotLookupEntryId, ex2, storeSession, this, "{0}. MapiException = {1}.", new object[]
                {
                    string.Format("Unable to lookup Local Directory EntryID", new object[0]),
                    ex2
                });
            }
            finally
            {
                try
                {
                    if (storeSession != null)
                    {
                        storeSession.EndMapiCall();
                        if (flag)
                        {
                            storeSession.EndServerHealthCall();
                        }
                    }
                }
                finally
                {
                    if (StorageGlobals.MapiTestHookAfterCall != null)
                    {
                        StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                    }
                }
            }
            StoreObjectId messageId = StoreObjectId.FromProviderSpecificId(entryId, StoreObjectType.Message);

            this.directoryMessage = MessageItem.Bind(session, messageId, new PropertyDefinition[]
            {
                InternalSchema.LocalDirectory
            });
            try
            {
                this.directoryMessage.OpenAsReadWrite();
                try
                {
                    using (Stream stream = this.directoryMessage.OpenPropertyStream(InternalSchema.LocalDirectory, PropertyOpenMode.ReadOnly))
                    {
                        long length = stream.Length;
                        using (BinaryReader binaryReader = new BinaryReader(stream))
                        {
                            while (stream.Position < length)
                            {
                                ExternalUser item;
                                if (ExternalUserCollection.TryReadEntry(binaryReader, out item) && !this.Contains(item))
                                {
                                    this.data.Add(item);
                                }
                            }
                        }
                    }
                }
                catch (ObjectNotFoundException)
                {
                }
                catch (EndOfStreamException)
                {
                }
            }
            catch (StoragePermanentException)
            {
                if (this.directoryMessage != null)
                {
                    this.directoryMessage.Dispose();
                }
                throw;
            }
            catch (StorageTransientException)
            {
                if (this.directoryMessage != null)
                {
                    this.directoryMessage.Dispose();
                }
                throw;
            }
            StorageGlobals.TraceConstructIDisposable(this);
            this.disposeTracker = this.GetDisposeTracker();
        }
Пример #21
0
 private static SharedFolderDataRecipient[] GetExternalIdentities(ExternalUserCollection externalUserCollection, ValidRecipient[] recipients)
 {
     SharedFolderDataRecipient[] result = Array.ConvertAll <ValidRecipient, SharedFolderDataRecipient>(recipients, (ValidRecipient recipient) => SharedFolderDataEncryption.GetExternalIdentity(externalUserCollection, recipient));
     externalUserCollection.Save();
     return(result);
 }
Пример #22
0
        private PermissionSecurityPrincipal CreatePermissionSecurityPrincipal(string recipient, ExternalUserCollection externalUserCollection)
        {
            ExternalUser externalUser = externalUserCollection.FindExternalUser(new SmtpAddress(recipient));

            if (externalUser == null)
            {
                return(null);
            }
            return(new PermissionSecurityPrincipal(externalUser));
        }
Пример #23
0
 internal ExternalUser TryGetExternalUser(byte[] memberEntryId, ref ExternalUserCollection externalUsers)
 {
     if (memberEntryId != null)
     {
         MailboxSession mailboxSession = this.Session as MailboxSession;
         if (externalUsers == null && mailboxSession != null)
         {
             externalUsers = mailboxSession.GetExternalUsers();
         }
         if (externalUsers != null)
         {
             try
             {
                 byte[]       binaryForm = null;
                 StoreSession session    = this.Session;
                 bool         flag       = false;
                 try
                 {
                     if (session != null)
                     {
                         session.BeginMapiCall();
                         session.BeginServerHealthCall();
                         flag = true;
                     }
                     if (StorageGlobals.MapiTestHookBeforeCall != null)
                     {
                         StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                     }
                     binaryForm = MapiStore.GetLocalDirectorySIDFromAddressBookEntryId(memberEntryId);
                 }
                 catch (MapiPermanentException ex)
                 {
                     throw StorageGlobals.TranslateMapiException(ServerStrings.InvalidPermissionsEntry, ex, session, this, "{0}. MapiException = {1}.", new object[]
                     {
                         string.Format("ACL table has invalid entry id.", new object[0]),
                         ex
                     });
                 }
                 catch (MapiRetryableException ex2)
                 {
                     throw StorageGlobals.TranslateMapiException(ServerStrings.InvalidPermissionsEntry, ex2, session, this, "{0}. MapiException = {1}.", new object[]
                     {
                         string.Format("ACL table has invalid entry id.", new object[0]),
                         ex2
                     });
                 }
                 finally
                 {
                     try
                     {
                         if (session != null)
                         {
                             session.EndMapiCall();
                             if (flag)
                             {
                                 session.EndServerHealthCall();
                             }
                         }
                     }
                     finally
                     {
                         if (StorageGlobals.MapiTestHookAfterCall != null)
                         {
                             StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                         }
                     }
                 }
                 SecurityIdentifier sid = new SecurityIdentifier(binaryForm, 0);
                 return(externalUsers.FindExternalUser(sid));
             }
             catch (ObjectNotFoundException)
             {
             }
         }
     }
     return(null);
 }
Пример #24
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()));
        }