// Token: 0x06001A01 RID: 6657 RVA: 0x0005DFA0 File Offset: 0x0005C1A0
        protected virtual IEnumerable <RmsTemplate> AcquireRmsTemplates(OrganizationId organizationId)
        {
            this.HandleSimultaneousExpensiveRmsTemplateCalls(organizationId);
            IEnumerable <RmsTemplate> result;

            try
            {
                IEnumerable <RmsTemplate> enumerable;
                if (RmsClientManager.IRMConfig.IsClientAccessServerEnabledForTenant(organizationId))
                {
                    enumerable = RmsClientManager.AcquireRmsTemplates(organizationId, false);
                }
                else
                {
                    enumerable = DrmEmailConstants.EmptyTemplateArray;
                }
                result = enumerable;
            }
            finally
            {
                if (GetComplianceConfiguration.organizationsDoingExpensiveRetrivals.Contains(organizationId))
                {
                    lock (GetComplianceConfiguration.organizationsDoingExpensiveRetrivals)
                    {
                        GetComplianceConfiguration.organizationsDoingExpensiveRetrivals.Remove(organizationId);
                    }
                }
            }
            return(result);
        }
        public static LicenseIdentity GetLicenseIdentity(RmsClientManagerContext context, string recipientAddress)
        {
            ArgumentValidator.ThrowIfNull("context", context);
            ArgumentValidator.ThrowIfNullOrEmpty("recipientAddress", recipientAddress);
            ADRawEntry adrawEntry;

            try
            {
                adrawEntry = context.ResolveRecipient(recipientAddress);
            }
            catch (ADTransientException innerException)
            {
                throw new ExchangeConfigurationException(ServerStrings.FailedToReadUserConfig(recipientAddress), innerException);
            }
            catch (ADOperationException innerException2)
            {
                throw new RightsManagementException(RightsManagementFailureCode.ADUserNotFound, ServerStrings.FailedToReadUserConfig(recipientAddress), innerException2);
            }
            if (adrawEntry == null)
            {
                throw new RightsManagementException(RightsManagementFailureCode.ADUserNotFound, ServerStrings.FailedToReadUserConfig(recipientAddress));
            }
            List <string> federatedEmailAddresses = RmsClientManagerUtils.GetFederatedEmailAddresses(context.OrgId, (ProxyAddressCollection)adrawEntry[ADRecipientSchema.EmailAddresses]);

            if (federatedEmailAddresses.Count == 0)
            {
                RmsClientManager.TraceFail(null, context.SystemProbeId, "GetLicenseIdentity: User {0} doesn't have any SMTP proxy address from a domain that is federated.", new object[]
                {
                    recipientAddress
                });
                throw new RightsManagementException(RightsManagementFailureCode.ADUserNotFederated, DirectoryStrings.UserHasNoSmtpProxyAddressWithFederatedDomain);
            }
            return(new LicenseIdentity(federatedEmailAddresses[0], federatedEmailAddresses.ToArray()));
        }
Exemple #3
0
 private void ValidateForEnterprise(IRMConfiguration config)
 {
     if (config.ExternalLicensingEnabled && !ExternalAuthentication.GetCurrent().Enabled)
     {
         base.WriteError(new OrganizationNotFederatedException(), ErrorCategory.InvalidOperation, base.Identity);
     }
     if (config.InternalLicensingEnabled)
     {
         Uri rmsserviceLocation = RmsClientManager.GetRMSServiceLocation(OrganizationId.ForestWideOrgId, ServiceType.Certification);
         if (rmsserviceLocation == null)
         {
             base.WriteError(new NoRMSServersFoundException(), ErrorCategory.InvalidOperation, base.Identity);
         }
         this.ValidateRmsVersion(rmsserviceLocation, ServiceType.CertificationService);
         this.ValidateRmsVersion(rmsserviceLocation, ServiceType.LicensingService);
     }
     if (!MultiValuedPropertyBase.IsNullOrEmpty(config.LicensingLocation))
     {
         foreach (Uri uri in config.LicensingLocation)
         {
             if (string.IsNullOrEmpty(RMUtil.ConvertUriToLicenseUrl(uri)))
             {
                 base.WriteError(new RmsUrlIsInvalidException(uri), ErrorCategory.InvalidOperation, base.Identity);
             }
             this.ValidateRmsVersion(uri, ServiceType.LicensingService);
         }
     }
 }
Exemple #4
0
        public static IEnumerable <RmsTemplate> GetRmsTemplates(OrganizationId organizationId)
        {
            bool flag = false;
            IEnumerable <RmsTemplate> result;

            try
            {
                if (!RmsClientManager.IRMConfig.IsInternalLicensingEnabledForTenant(organizationId))
                {
                    RmsTemplateReaderCache.negativeCacheTimeoutForFirstOrg = ExDateTime.MinValue;
                    throw new AirSyncPermanentException(StatusCode.IRM_FeatureDisabled, false)
                          {
                              ErrorStringForProtocolLogger = "rtrcGrtInternalLicensingDisabled"
                          };
                }
                if (organizationId == OrganizationId.ForestWideOrgId && RmsTemplateReaderCache.negativeCacheTimeoutForFirstOrg > ExDateTime.UtcNow)
                {
                    AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, null, "Found RMSTemplateReader for first org in negative cache");
                    throw new AirSyncPermanentException(StatusCode.IRM_TransientError, false)
                          {
                              ErrorStringForProtocolLogger = "rtrcGrtNegativeCacheHit"
                          };
                }
                result = RmsClientManager.AcquireRmsTemplates(organizationId, false);
            }
            catch (ExchangeConfigurationException ex)
            {
                AirSyncDiagnostics.TraceError <ExchangeConfigurationException>(ExTraceGlobals.RequestsTracer, null, "ExchangeConfigurationException encountered while acquiring RMS templates: {0}", ex);
                flag = true;
                throw new AirSyncPermanentException(StatusCode.IRM_TransientError, ex, false)
                      {
                          ErrorStringForProtocolLogger = "rtrcGrtExchangeConfigurationException"
                      };
            }
            catch (RightsManagementException ex2)
            {
                AirSyncDiagnostics.TraceError <RightsManagementException>(ExTraceGlobals.RequestsTracer, null, "RightsManagementException encountered while acquiring RMS templates: {0}", ex2);
                if (ex2.FailureCode != RightsManagementFailureCode.InternalLicensingDisabled)
                {
                    flag = true;
                }
                throw new AirSyncPermanentException(ex2.IsPermanent ? StatusCode.IRM_PermanentError : StatusCode.IRM_TransientError, ex2, false)
                      {
                          ErrorStringForProtocolLogger = "rtrcGrtRightsManagementException" + ex2.FailureCode.ToString()
                      };
            }
            finally
            {
                if (organizationId == OrganizationId.ForestWideOrgId && flag)
                {
                    RmsTemplateReaderCache.negativeCacheTimeoutForFirstOrg = ExDateTime.UtcNow.Add(GlobalSettings.NegativeRmsTemplateCacheExpirationInterval);
                }
            }
            return(result);
        }
Exemple #5
0
 public bool Decode(OutboundConversionOptions options, bool acquireLicense)
 {
     this.CheckDisposed("Decode");
     Util.ThrowOnNullArgument(options, "options");
     this.decryptionStatus = RightsManagedMessageDecryptionStatus.Success;
     if (this.decodedItem != null)
     {
         return(true);
     }
     if (this.InternalSession == null)
     {
         this.decryptionStatus = RightsManagedMessageDecryptionStatus.NotSupported;
         throw new InvalidOperationException("Decoding of in-memory messages is not supported.");
     }
     RightsManagedMessageItem.CheckSession(this.InternalSession);
     this.SetConversionOptions(options);
     using (DisposeGuard disposeGuard = default(DisposeGuard))
     {
         try
         {
             MessageItem messageItem = ItemConversion.OpenRestrictedContent(this, this.orgId, acquireLicense, out this.licenseAcquired, out this.useLicenseValue, out this.restrictionInfo);
             if (messageItem == null)
             {
                 ExTraceGlobals.StorageTracer.TraceError(0L, "Failed to decode protected message - no user license is present.");
                 throw new RightsManagementPermanentException(RightsManagementFailureCode.UnknownFailure, ServerStrings.GenericFailureRMDecryption);
             }
             disposeGuard.Add <MessageItem>(messageItem);
             this.UpdateEffectiveRights();
             this.conversationOwner = new Participant(this.restrictionInfo.ConversationOwner, this.restrictionInfo.ConversationOwner, "SMTP");
             this.CheckPermission(ContentRight.View);
             messageItem.CoreItem.TopLevelItem = (base.CoreItem.TopLevelItem ?? base.CoreItem);
             this.serverUseLicense             = (messageItem.TryGetProperty(MessageItemSchema.DRMServerLicense) as string);
             this.publishLicense = (messageItem.TryGetProperty(MessageItemSchema.DrmPublishLicense) as string);
             this.rmsTemplate    = RmsTemplate.CreateFromPublishLicense(this.publishLicense);
             MsgToRpMsgConverter.CallRM(delegate
             {
                 this.publishedByExternalRMS = !RmsClientManager.IsPublishedByOrganizationRMS(this.orgId, this.publishLicense);
             }, ServerStrings.FailedToCheckPublishLicenseOwnership(this.orgId.ToString()));
             this.decodedItem = messageItem;
             disposeGuard.Success();
         }
         catch (RightsManagementPermanentException exception)
         {
             this.decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception);
             throw;
         }
         catch (RightsManagementTransientException exception2)
         {
             this.decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception2);
             throw;
         }
     }
     return(true);
 }
 internal void AsyncAcquireLicenses(OrganizationId organizationId, OwaStoreObjectId messageId, string publishLicense, string userSmtpAddress, SecurityIdentifier userSid, RecipientTypeDetails userType, string requestCorrelator)
 {
     if (organizationId == null)
     {
         throw new ArgumentNullException("organizationId");
     }
     if (messageId == null)
     {
         throw new ArgumentNullException("messageId");
     }
     if (string.IsNullOrEmpty(publishLicense))
     {
         throw new ArgumentNullException("publishLicense");
     }
     if (string.IsNullOrEmpty(userSmtpAddress))
     {
         throw new ArgumentNullException("userSmtpAddress");
     }
     if (userSid == null)
     {
         throw new ArgumentNullException("userSid");
     }
     if (string.IsNullOrEmpty("requestCorrelator"))
     {
         throw new ArgumentNullException("requestCorrelator");
     }
     this.licensingResponseQueue.InitializeErrorIconUrl(this.userContext.GetThemeFileUrl(ThemeFileId.Error));
     this.userCulture = this.userContext.UserCulture;
     this.licensingResponseQueue.InitializeUserCulture(this.userContext.UserCulture);
     try
     {
         IrmLicensingManager.Tracer.TraceDebug((long)this.GetHashCode(), "AsyncAcquireLicenses: issuing async license req. orgId: {0}; msgId: {1}; userId: {2}; correlator: {3}", new object[]
         {
             organizationId,
             messageId,
             userSmtpAddress,
             requestCorrelator
         });
         RmsClientManager.BeginAcquireUseLicenseAndUsageRights(new RmsClientManagerContext(organizationId, RmsClientManagerContext.ContextId.MessageId, messageId.ToString(), publishLicense), publishLicense, userSmtpAddress, userSid, userType, new AsyncCallback(this.AcquireUseLicenseAndUsageRightsCallback), new IrmLicensingManager.AsyncState(messageId, requestCorrelator));
     }
     catch (ExchangeConfigurationException arg)
     {
         IrmLicensingManager.Tracer.TraceError <string, ExchangeConfigurationException>((long)this.GetHashCode(), "AsyncAcquireLicenses: exception at BeginAcquireUseLicenseAndUsageRights.  Correlator: {0}; Exception: {1}", requestCorrelator, arg);
         this.HandleExchangeConfigurationException(messageId, requestCorrelator);
     }
     catch (RightsManagementException ex)
     {
         IrmLicensingManager.Tracer.TraceError <string, RightsManagementException>((long)this.GetHashCode(), "AsyncAcquireLicenses: exception at BeginAcquireUseLicenseAndUsageRights.  Correlator: {0}; Exception: {1}", requestCorrelator, ex);
         this.HandleRightsManagementException(ex, messageId, requestCorrelator);
     }
 }
Exemple #7
0
        private static void AcquireServerLicensingMexCallback(ICancelableAsyncResult asyncResult)
        {
            RmsServerInfoManager.Tracer.TraceDebug(0L, "AcquireServerLicensingMexCallback invoked");
            ArgumentValidator.ThrowIfNull("asyncResult", asyncResult);
            ArgumentValidator.ThrowIfNull("asyncResult.AsyncState", asyncResult.AsyncState);
            AcquireServerInfoAsyncResult acquireServerInfoAsyncResult = asyncResult.AsyncState as AcquireServerInfoAsyncResult;

            if (acquireServerInfoAsyncResult == null)
            {
                throw new InvalidOperationException("asyncResult.AsyncState has to be type of AcquireServerInfoAsyncResult.");
            }
            acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.AcquireServerLicensingMexCallback);
            Exception ex = null;

            try
            {
                DownloadResult downloadResult = acquireServerInfoAsyncResult.HttpClient.EndDownload(asyncResult);
                acquireServerInfoAsyncResult.LatencyTracker.EndTrackRmsLatency(RmsOperationType.AcquireServerLicensingMexData);
                if (downloadResult.IsSucceeded)
                {
                    Uri targetUriFromResponse = RmsClientManagerUtils.GetTargetUriFromResponse(downloadResult.ResponseStream);
                    if (targetUriFromResponse == null)
                    {
                        ex = new RightsManagementException(RightsManagementFailureCode.FailedToExtractTargetUriFromMex, ServerStrings.FailedToFindTargetUriFromMExData(acquireServerInfoAsyncResult.ServerLicensingMExUri), acquireServerInfoAsyncResult.LicenseUri.ToString());
                    }
                    else
                    {
                        acquireServerInfoAsyncResult.ServerInfo.ServerLicensingWSTargetUri = TokenTarget.Fix(targetUriFromResponse);
                        RmsServerInfoManager.serverInfoMap.Add(acquireServerInfoAsyncResult.ServerInfo);
                    }
                }
                else
                {
                    RmsClientManager.TraceFail(null, acquireServerInfoAsyncResult.Context.SystemProbeId, "Failed to download data from server licensing MEx {0}.  Exception is {1}", new object[]
                    {
                        acquireServerInfoAsyncResult.ServerLicensingMExUri,
                        downloadResult.Exception
                    });
                    ex = new RightsManagementException(RightsManagementFailureCode.FailedToDownloadMexData, ServerStrings.FailedToDownloadServerLicensingMExData(downloadResult.ResponseUri), downloadResult.Exception, acquireServerInfoAsyncResult.LicenseUri.ToString());
                    ((RightsManagementException)ex).IsPermanent = !downloadResult.IsRetryable;
                }
            }
            finally
            {
                acquireServerInfoAsyncResult.Release();
            }
            RmsServerInfoManager.Tracer.TraceDebug(0L, "AcquireServiceLocationCallback: Invoking find service location callbacks");
            RmsServerInfoManager.outstandingFindServiceLocationCalls.InvokeCallbacks(acquireServerInfoAsyncResult.LicenseUri, ex);
        }
        private IEnumerable <RmsTemplate> AcquireRmsTemplates()
        {
            if (this.orgId == OrganizationId.ForestWideOrgId)
            {
                return(RmsClientManager.AcquireRmsTemplates(this.orgId, true));
            }
            if (this.irmConfiguration == null || (!this.irmConfiguration.InternalLicensingEnabled && !this.displayTemplatesIfInternalLicensingDisabled))
            {
                return(DrmEmailConstants.EmptyTemplateArray);
            }
            RMSTrustedPublishingDomain rmstrustedPublishingDomain = this.FindTPD();

            if (rmstrustedPublishingDomain == null)
            {
                return(DrmEmailConstants.EmptyTemplateArray);
            }
            List <RmsTemplate> list = null;

            if (!MultiValuedPropertyBase.IsNullOrEmpty(rmstrustedPublishingDomain.RMSTemplates))
            {
                list = new List <RmsTemplate>(rmstrustedPublishingDomain.RMSTemplates.Count + 2);
                using (MultiValuedProperty <string> .Enumerator enumerator = rmstrustedPublishingDomain.RMSTemplates.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        string          encodedTemplate = enumerator.Current;
                        RmsTemplateType type            = RmsTemplateType.Archived;
                        string          templateXrml    = RMUtil.DecompressTemplate(encodedTemplate, out type);
                        if (this.ShouldFetch(type))
                        {
                            list.Add(RmsTemplate.CreateServerTemplateFromTemplateDefinition(templateXrml, type));
                        }
                    }
                    goto IL_CE;
                }
            }
            list = new List <RmsTemplate>(2);
IL_CE:
            if (this.typeToFetch != RmsTemplateType.Archived && rmstrustedPublishingDomain.Default)
            {
                list.Add(RmsTemplate.DoNotForward);
                if (this.irmConfiguration.InternetConfidentialEnabled)
                {
                    list.Add(RmsTemplate.InternetConfidential);
                }
            }
            return(list);
        }
Exemple #9
0
        private static RmsTemplate LookupRmsTemplate(Guid templateId, MailboxSession session)
        {
            OrganizationId organizationId = session.MailboxOwner.MailboxInfo.OrganizationId;

            IrmUtils.ThrowIfInternalLicensingDisabled(organizationId);
            IEnumerable <RmsTemplate> source = RmsClientManager.AcquireRmsTemplates(organizationId, false);
            RmsTemplate result;

            try
            {
                result = source.SingleOrDefault((RmsTemplate template) => template.Id.Equals(templateId));
            }
            catch (InvalidOperationException)
            {
                throw new RightsManagementPermanentException(Strings.ErrorRightsManagementDuplicateTemplateId(templateId.ToString()), null);
            }
            return(result);
        }
 private bool TryGetTemplate()
 {
     this.result.SetTask(Strings.InfoGetTemplate);
     try
     {
         RmsClientManager.AcquireRMSTemplate(this.context, RmsTemplate.DoNotForward.Id);
         this.result.SetSuccessResult(Strings.InfoTemplate);
     }
     catch (ExchangeConfigurationException ex)
     {
         this.result.SetFailureResult(this.datacenter ? Strings.ErrorFailedToGetTemplateTenant : Strings.ErrorFailedToGetTemplateEnterprise, ex, this.encryptionEnabled);
         return(false);
     }
     catch (RightsManagementException ex2)
     {
         this.result.SetFailureResult(this.datacenter ? Strings.ErrorFailedToGetTemplateTenant : Strings.ErrorFailedToGetTemplateEnterprise, ex2, this.encryptionEnabled);
         return(false);
     }
     return(true);
 }
 public IEnumerable <RmsTemplate> GetRmsTemplates()
 {
     this.errorAcquiringTemplates = false;
     if (this.IsInternalLicensingEnabled)
     {
         try
         {
             return(RmsClientManager.AcquireRmsTemplates(this.organizationId, false));
         }
         catch (ExchangeConfigurationException arg)
         {
             ExTraceGlobals.CoreTracer.TraceError <ExchangeConfigurationException>(0L, "ExchangeConfigurationException while loading RMS templates: {0}", arg);
             this.errorAcquiringTemplates = true;
         }
         catch (RightsManagementException arg2)
         {
             ExTraceGlobals.CoreTracer.TraceError <RightsManagementException>(0L, "RightsManagementException while Loading RMS templates: {0}", arg2);
             this.errorAcquiringTemplates = true;
         }
     }
     return(RmsTemplateReader.EmptyRmsTemplateList);
 }
        private static ADOperationResult TryGetOrganizationIdFromExternalDirectoryOrgId(Guid externalDirectoryOrgId, out OrganizationId organizationId)
        {
            RmsClientManagerUtils.< > c__DisplayClass10 CS$ < > 8__locals1 = new RmsClientManagerUtils.< > c__DisplayClass10();
            CS$ < > 8__locals1.externalDirectoryOrgId = externalDirectoryOrgId;
            if (CS$ < > 8__locals1.externalDirectoryOrgId == Guid.Empty)
            {
                throw new ArgumentException("Guid.Empty is not a valid external directory org id", "externalDirectoryOrgId");
            }
            RmsClientManagerUtils.< > c__DisplayClass10 CS$ < > 8__locals2 = CS$ < > 8__locals1;
            OrganizationId localOrgId;

            organizationId = (localOrgId = null);
            CS$ < > 8__locals2.localOrgId = localOrgId;
            try
            {
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    ITenantConfigurationSession tenantConfigurationSession = DirectorySessionFactory.Default.CreateTenantConfigurationSession(ConsistencyMode.IgnoreInvalid, CS$ < > 8__locals1.externalDirectoryOrgId, 1406, "TryGetOrganizationIdFromExternalDirectoryOrgId", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\rightsmanagement\\RmsClientManagerUtils.cs");
                    if (tenantConfigurationSession == null)
                    {
                        return;
                    }
                    Organization orgContainer = tenantConfigurationSession.GetOrgContainer();
                    if (orgContainer != null)
                    {
                        CS$ < > 8__locals1.localOrgId = orgContainer.OrganizationId;
                        return;
                    }
                    throw new DataSourceOperationException(ServerStrings.FailedToGetOrgContainer(CS$ < > 8__locals1.externalDirectoryOrgId));
                });
            }
            catch (TransientException ex)
            {
                RmsClientManager.TraceFail(0, Guid.Empty, "Cannot resolve the External OrgID {0} - exception is {1}", new object[]
                {
                    CS$ < > 8__locals1.externalDirectoryOrgId,
                    ex
                });
Exemple #13
0
        public MessageItem ConvertRpmsgToMsg(MessageItem rightsProtectedMessage, string useLicense, SafeRightsManagementHandle enablingPrincipalRac)
        {
            ExTraceGlobals.RightsManagementTracer.TraceDebug((long)this.GetHashCode(), "RpMsgToMsgConverter::ConvertRpmsgToMsg");
            if (string.IsNullOrEmpty(useLicense))
            {
                throw new ArgumentNullException("useLicense");
            }
            if (enablingPrincipalRac == null)
            {
                throw new ArgumentNullException("enablingPrincipalRac");
            }
            if (enablingPrincipalRac.IsInvalid)
            {
                throw new ArgumentException("enablingPrincipalRac");
            }
            SafeRightsManagementHandle safeRightsManagementHandle = null;

            try
            {
                RmsClientManager.BindUseLicenseForDecryption(enablingPrincipalRac, useLicense, this.drmMsgContainer.PublishLicense, out safeRightsManagementHandle);
                this.DecryptMsg(rightsProtectedMessage, useLicense, safeRightsManagementHandle);
            }
            finally
            {
                if (safeRightsManagementHandle != null)
                {
                    safeRightsManagementHandle.Close();
                    safeRightsManagementHandle = null;
                }
            }
            if (this.decryptedItem == null)
            {
                throw new RightsManagementPermanentException(RightsManagementFailureCode.UnknownFailure, ServerStrings.GenericFailureRMDecryption);
            }
            return(this.decryptedItem);
        }
 private void AcquireUseLicenseAndUsageRightsCallback(IAsyncResult asyncResult)
 {
     if (asyncResult == null)
     {
         throw new ArgumentNullException("asyncResult");
     }
     if (asyncResult.AsyncState == null)
     {
         IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: asyncResult.AsyncState is null.");
         throw new InvalidOperationException("asyncResult.AsyncState must NOT be null.");
     }
     IrmLicensingManager.AsyncState asyncState = (IrmLicensingManager.AsyncState)asyncResult.AsyncState;
     try
     {
         IrmLicensingManager.Tracer.TraceDebug <OwaStoreObjectId>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: calling EndAcquireUseLicenseAndUsageRights to get results for message {0}", asyncState.MessageId);
         UseLicenseAndUsageRights useLicenseAndUsageRights = RmsClientManager.EndAcquireUseLicenseAndUsageRights(asyncResult);
         if (string.IsNullOrEmpty(useLicenseAndUsageRights.UseLicense))
         {
             IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: Use license is null/empty");
             throw new InvalidOperationException("Use license must NOT be null/empty");
         }
         if (this.userContext.State != UserContextState.Active)
         {
             IrmLicensingManager.Tracer.TraceDebug((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: User context is no longer active.  Bailing out.");
         }
         else
         {
             SafeRightsManagementHandle safeRightsManagementHandle = null;
             try
             {
                 RmsClientManager.BindUseLicenseForDecryption(new RmsClientManagerContext(useLicenseAndUsageRights.OrganizationId, RmsClientManagerContext.ContextId.MessageId, asyncState.MessageId.ToString(), null), useLicenseAndUsageRights.LicensingUri, useLicenseAndUsageRights.UseLicense, useLicenseAndUsageRights.PublishingLicense, out safeRightsManagementHandle);
             }
             finally
             {
                 if (safeRightsManagementHandle != null)
                 {
                     safeRightsManagementHandle.Close();
                 }
             }
             bool flag = false;
             try
             {
                 this.userContext.Lock();
                 flag = true;
                 using (Item item = Item.Bind(asyncState.MessageId.GetSession(this.userContext), asyncState.MessageId.StoreObjectId, ItemBindOption.None))
                 {
                     MessageItem messageItem = item as MessageItem;
                     if (messageItem == null)
                     {
                         IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: bound item is not a message.  Ignoring it.");
                     }
                     else
                     {
                         messageItem.OpenAsReadWrite();
                         messageItem[MessageItemSchema.DRMRights]     = useLicenseAndUsageRights.UsageRights;
                         messageItem[MessageItemSchema.DRMExpiryTime] = useLicenseAndUsageRights.ExpiryTime;
                         if (!DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense))
                         {
                             using (Stream stream = messageItem.OpenPropertyStream(MessageItemSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create))
                             {
                                 DrmEmailCompression.CompressUseLicense(useLicenseAndUsageRights.UseLicense, stream);
                             }
                         }
                         messageItem[MessageItemSchema.DRMPropsSignature] = useLicenseAndUsageRights.DRMPropsSignature;
                         RightsManagedMessageItem rightsManagedMessageItem = messageItem as RightsManagedMessageItem;
                         if (rightsManagedMessageItem != null && rightsManagedMessageItem.IsRestricted && !rightsManagedMessageItem.TryDecode(Utilities.CreateOutboundConversionOptions(this.userContext), false).Failed)
                         {
                             bool flag2 = false;
                             foreach (AttachmentHandle attachmentHandle in rightsManagedMessageItem.ProtectedAttachmentCollection)
                             {
                                 if (!attachmentHandle.IsInline)
                                 {
                                     flag2 = true;
                                     break;
                                 }
                             }
                             messageItem[MessageItemSchema.AllAttachmentsHidden] = !flag2;
                             rightsManagedMessageItem.AbandonChangesOnProtectedData();
                         }
                         messageItem.Save(SaveMode.ResolveConflicts);
                         if (DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense))
                         {
                             this.EnqueueLicensingError(asyncState.MessageId, SanitizedHtmlString.FromStringId(-1616549110, this.userCulture), asyncState.RequestCorrelator);
                         }
                         else
                         {
                             this.EnqueueLicenseAcquired(asyncState.MessageId, asyncState.RequestCorrelator);
                         }
                     }
                 }
             }
             finally
             {
                 if (this.userContext.LockedByCurrentThread() && flag)
                 {
                     this.userContext.Unlock();
                 }
             }
         }
     }
     catch (OwaLockTimeoutException arg)
     {
         IrmLicensingManager.Tracer.TraceError <OwaLockTimeoutException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: timed-out at acquiring user context lock.  Exception: {0}", arg);
         this.EnqueueLicensingError(asyncState.MessageId, new SanitizedHtmlString(LocalizedStrings.GetNonEncoded(858913858)), asyncState.RequestCorrelator);
     }
     catch (ExchangeConfigurationException arg2)
     {
         IrmLicensingManager.Tracer.TraceError <ExchangeConfigurationException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", arg2);
         this.HandleExchangeConfigurationException(asyncState.MessageId, asyncState.RequestCorrelator);
     }
     catch (RightsManagementException ex)
     {
         IrmLicensingManager.Tracer.TraceError <RightsManagementException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", ex);
         this.HandleRightsManagementException(ex, asyncState.MessageId, asyncState.RequestCorrelator);
     }
     catch (StoragePermanentException ex2)
     {
         IrmLicensingManager.Tracer.TraceError <StoragePermanentException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", ex2);
         this.EnqueueLicensingError(asyncState.MessageId, SanitizedHtmlString.Format(LocalizedStrings.GetHtmlEncoded(994351595, this.userCulture), new object[]
         {
             ex2.Message
         }), asyncState.RequestCorrelator);
     }
     catch (TransientException arg3)
     {
         IrmLicensingManager.Tracer.TraceError <TransientException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", arg3);
         this.EnqueueLicensingError(asyncState.MessageId, new SanitizedHtmlString(LocalizedStrings.GetNonEncoded(858913858)), asyncState.RequestCorrelator);
     }
     catch (Exception ex3)
     {
         IrmLicensingManager.Tracer.TraceError <Exception>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", ex3);
         if (Globals.SendWatsonReports)
         {
             IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: sending watson report...");
             string data = string.Format("OWA version: {0}; Message Id: {1}", Globals.ApplicationVersion, asyncState.MessageId.ToBase64String());
             ExWatson.AddExtraData(data);
             ExWatson.SendReport(ex3, ReportOptions.None, null);
             IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: watson report has been sent.");
         }
     }
 }
Exemple #15
0
        // Token: 0x0600012F RID: 303 RVA: 0x00007734 File Offset: 0x00005934
        private static void LicenseMessage(IExchangePrincipal userPrincipal, MessageItem item)
        {
            string publishLicense;

            using (Attachment attachment = item.AttachmentCollection.Open(item.AttachmentCollection.GetHandles()[0]))
            {
                using (Stream contentStream = ((StreamAttachmentBase)attachment).GetContentStream(PropertyOpenMode.ReadOnly))
                {
                    using (DrmEmailMessageContainer drmEmailMessageContainer = new DrmEmailMessageContainer())
                    {
                        try
                        {
                            drmEmailMessageContainer.Load(contentStream, (object param0) => Streams.CreateTemporaryStorageStream());
                            publishLicense = drmEmailMessageContainer.PublishLicense;
                        }
                        catch (InvalidRpmsgFormatException arg)
                        {
                            LicensingProcessor.Tracer.TraceError <object, InvalidRpmsgFormatException>(0L, "{0}: LicensingProcessor:Failed to load RPMSG. {1}", TraceContext.Get(), arg);
                            return;
                        }
                    }
                }
            }
            UseLicenseAndUsageRights useLicenseAndUsageRights;

            try
            {
                useLicenseAndUsageRights = RmsClientManager.AcquireUseLicenseAndUsageRights(new RmsClientManagerContext(userPrincipal.MailboxInfo.OrganizationId, RmsClientManagerContext.ContextId.MessageId, item.InternetMessageId, publishLicense), publishLicense, userPrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), userPrincipal.Sid, userPrincipal.RecipientTypeDetails);
            }
            catch (RightsManagementException ex)
            {
                LicensingProcessor.Tracer.TraceError <object, RightsManagementException>(0L, "{0}: LicensingProcessor:Failed to license message. {1}", TraceContext.Get(), ex);
                if (!ex.IsPermanent)
                {
                    throw new StorageTransientException(Strings.FailedToAcquireUseLicense, ex);
                }
                return;
            }
            catch (ExchangeConfigurationException ex2)
            {
                LicensingProcessor.Tracer.TraceError <object, ExchangeConfigurationException>(0L, "{0}: LicensingProcessor:Failed to license message. {1}", TraceContext.Get(), ex2);
                throw new StorageTransientException(Strings.FailedToReadIRMConfig, ex2);
            }
            LicensingProcessor.Tracer.TraceDebug(0L, "{0}: LicensingProcesssor: Saving licenses", new object[]
            {
                TraceContext.Get()
            });
            item.OpenAsReadWrite();
            item[MessageItemSchema.DRMRights]     = useLicenseAndUsageRights.UsageRights;
            item[MessageItemSchema.DRMExpiryTime] = useLicenseAndUsageRights.ExpiryTime;
            if (!DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense))
            {
                using (Stream stream = item.OpenPropertyStream(MessageItemSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create))
                {
                    DrmEmailCompression.CompressUseLicense(useLicenseAndUsageRights.UseLicense, stream);
                }
            }
            item[MessageItemSchema.DRMPropsSignature] = useLicenseAndUsageRights.DRMPropsSignature;
            item.Save(SaveMode.ResolveConflicts);
            LicensingProcessor.Tracer.TraceDebug(0L, "{0}: LicensingProcesssor: message was saved successfully", new object[]
            {
                TraceContext.Get()
            });
        }
        private bool TryGetULAndPreL()
        {
            this.result.SetTask(Strings.InfoGetLicensingUri);
            try
            {
                this.licensingUris = RmsClientManager.IRMConfig.GetTenantLicensingLocations(this.organizationId);
                if (this.licensingUris != null)
                {
                    for (int i = 0; i < this.licensingUris.Count; i++)
                    {
                        this.licensingUris[i] = RmsoProxyUtil.GetLicenseServerRedirectUrl(this.licensingUris[i]);
                    }
                }
            }
            catch (RightsManagementException ex)
            {
                this.result.SetFailureResult(Strings.ErrorFailedToGetLicensingUri, ex, this.encryptionEnabled);
                return(false);
            }
            catch (ExchangeConfigurationException ex2)
            {
                this.result.SetFailureResult(Strings.ErrorFailedToGetLicensingUri, ex2, this.encryptionEnabled);
                return(false);
            }
            if (this.licensingUris == null || this.licensingUris.Count == 0)
            {
                this.result.SetFailureResult(Strings.ErrorFailedToGetLicensingUri, null, this.encryptionEnabled);
                return(false);
            }
            foreach (Uri uri in this.licensingUris)
            {
                this.result.SetSuccessResult(Strings.InfoLicensingUri(uri));
            }
            bool flag = true;

            foreach (Uri uri2 in this.licensingUris)
            {
                this.result.SetTask(Strings.InfoCheckRmsVersion(uri2));
                try
                {
                    if (this.ValidateRmsVersion(uri2, ServiceType.LicensingService))
                    {
                        this.result.SetSuccessResult(Strings.InfoRmsVersionChecked);
                    }
                    else
                    {
                        this.result.SetFailureResult(Strings.ErrorFailedRmsVersionCheck, null, this.encryptionEnabled);
                        flag = false;
                    }
                }
                catch (RightsManagementException ex3)
                {
                    this.result.SetFailureResult(Strings.ErrorFailedRmsVersionCheck, ex3, this.encryptionEnabled);
                    flag = false;
                }
                catch (ExchangeConfigurationException ex4)
                {
                    this.result.SetFailureResult(Strings.ErrorFailedRmsVersionCheckInitialization, ex4, this.encryptionEnabled);
                    flag = false;
                }
            }
            if (!flag)
            {
                return(false);
            }
            XmlNode[] issuanceLicense;
            flag = this.TryCreatePL(out issuanceLicense);
            if (!flag)
            {
                return(false);
            }
            if (!this.datacenter)
            {
                foreach (string text in this.recipientsAddress)
                {
                    this.result.SetTask(Strings.InfoGetPreL(text, this.publishingUri));
                    try
                    {
                        LicenseResponse[] array2 = RmsClientManager.AcquirePreLicense(this.context, this.publishingUri, issuanceLicense, new string[]
                        {
                            text
                        });
                        int num = array2.Length;
                        for (int k = 0; k < num; k++)
                        {
                            if (array2[k].Exception != null)
                            {
                                this.result.SetFailureResult(Strings.InfoPreLIndividual(array2[k].Exception.FailureCode), null, this.prelicensingEnabled);
                                flag = false;
                            }
                            else
                            {
                                this.result.SetSuccessResult(Strings.InfoPreL);
                            }
                        }
                    }
                    catch (ExchangeConfigurationException ex5)
                    {
                        this.result.SetFailureResult(Strings.ErrorFailedToGetPreL, ex5, this.prelicensingEnabled);
                        flag = false;
                    }
                    catch (RightsManagementException ex6)
                    {
                        this.result.SetFailureResult(Strings.ErrorFailedToGetPreL, ex6, this.prelicensingEnabled);
                        flag = false;
                    }
                }
            }
            this.result.SetTask(Strings.InfoGetUL(this.publishingUri));
            try
            {
                RmsClientManager.AcquireUseLicense(this.context, this.publishingUri, issuanceLicense, null);
                this.result.SetSuccessResult(Strings.InfoUL);
            }
            catch (ExchangeConfigurationException ex7)
            {
                this.result.SetFailureResult(this.datacenter ? Strings.ErrorFailedToGetULTenant : Strings.ErrorFailedToGetULEnterprise, ex7, this.licensingEnabled);
                flag = false;
            }
            catch (RightsManagementException ex8)
            {
                if (ex8.FailureCode == RightsManagementFailureCode.ServerRightNotGranted)
                {
                    this.result.SetFailureResult(Strings.ErrorFailedToGetULDueToInvalidSuperUserConfiguration, null, this.licensingEnabled);
                }
                else
                {
                    this.result.SetFailureResult(this.datacenter ? Strings.ErrorFailedToGetULTenant : Strings.ErrorFailedToGetULEnterprise, ex8, this.licensingEnabled);
                }
                flag = false;
            }
            return(flag);
        }
 private bool TryGetRacAndClc()
 {
     this.result.SetTask(Strings.InfoGetCertificationUri);
     try
     {
         this.certificationUri = RmsClientManager.GetRMSServiceLocation(this.organizationId, ServiceType.Certification);
         this.certificationUri = RmsoProxyUtil.GetCertificationServerRedirectUrl(this.certificationUri);
     }
     catch (RightsManagementException ex)
     {
         this.result.SetFailureResult(Strings.ErrorFailedToGetCertificationUri, ex, this.encryptionEnabled);
         return(false);
     }
     catch (ExchangeConfigurationException ex2)
     {
         this.result.SetFailureResult(Strings.ErrorFailedToGetCertificationUri, ex2, this.encryptionEnabled);
         return(false);
     }
     if (this.certificationUri == null)
     {
         this.result.SetFailureResult(Strings.ErrorFailedToGetCertificationUri, null, this.encryptionEnabled);
         return(false);
     }
     this.result.SetSuccessResult(Strings.InfoCertificationUri(this.certificationUri));
     this.result.SetTask(Strings.InfoCheckRmsVersion(this.certificationUri));
     try
     {
         if (this.ValidateRmsVersion(this.certificationUri, ServiceType.CertificationService))
         {
             this.result.SetSuccessResult(Strings.InfoRmsVersionChecked);
         }
         else
         {
             this.result.SetFailureResult(Strings.ErrorFailedRmsVersionCheck, null, this.encryptionEnabled);
         }
     }
     catch (RightsManagementException ex3)
     {
         this.result.SetFailureResult(Strings.ErrorFailedRmsVersionCheck, ex3, this.encryptionEnabled);
         return(false);
     }
     catch (ExchangeConfigurationException ex4)
     {
         this.result.SetFailureResult(Strings.ErrorFailedRmsVersionCheckInitialization, ex4, this.encryptionEnabled);
         return(false);
     }
     this.result.SetTask(Strings.InfoGetPublishingUri);
     try
     {
         this.publishingUri = RmsClientManager.GetRMSServiceLocation(this.organizationId, ServiceType.Publishing);
         this.publishingUri = RmsoProxyUtil.GetLicenseServerRedirectUrl(this.publishingUri);
     }
     catch (RightsManagementException ex5)
     {
         this.result.SetFailureResult(Strings.ErrorFailedToGetPublishingUri, ex5, this.encryptionEnabled);
         return(false);
     }
     catch (ExchangeConfigurationException ex6)
     {
         this.result.SetFailureResult(Strings.ErrorFailedToGetPublishingUri, ex6, this.encryptionEnabled);
         return(false);
     }
     if (this.publishingUri == null)
     {
         this.result.SetFailureResult(Strings.ErrorFailedToGetPublishingUri, null, this.encryptionEnabled);
         return(false);
     }
     this.result.SetSuccessResult(Strings.InfoPublishingUri(this.publishingUri));
     this.result.SetTask(Strings.InfoGetRacAndClc);
     try
     {
         this.tenantLicenses = RmsClientManager.AcquireTenantLicenses(this.context, this.publishingUri);
         this.result.SetSuccessResult(Strings.InfoRacAndClc);
     }
     catch (ExchangeConfigurationException ex7)
     {
         this.result.SetFailureResult(this.datacenter ? Strings.ErrorFailedToGetRacAndClcTenant : Strings.ErrorFailedToGetRacAndClcEnterprise, ex7, this.encryptionEnabled);
         return(false);
     }
     catch (RightsManagementException ex8)
     {
         this.result.SetFailureResult(this.datacenter ? Strings.ErrorFailedToGetRacAndClcTenant : Strings.ErrorFailedToGetRacAndClcEnterprise, ex8, this.encryptionEnabled);
         return(false);
     }
     return(true);
 }
        public static Stream OpenRestrictedAttachment(StreamAttachment sourceAttachment, OrganizationId orgId, string userIdentity, SecurityIdentifier userSid, RecipientTypeDetails userType, out UseLicenseAndUsageRights validatedUseLicenseAndUsageRights, out bool acquiredNewLicense)
        {
            StreamAttachment.< > c__DisplayClass2 CS$ < > 8__locals1 = new StreamAttachment.< > c__DisplayClass2();
            CS$ < > 8__locals1.sourceAttachment = sourceAttachment;
            CS$ < > 8__locals1.orgId            = orgId;
            CS$ < > 8__locals1.userIdentity     = userIdentity;
            CS$ < > 8__locals1.userSid          = userSid;
            CS$ < > 8__locals1.userType         = userType;
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.sourceAttachment, "sourceAttachment");
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.orgId, "orgId");
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.userIdentity, "userIdentity");
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.userSid, "userSid");
            if (!Enum.IsDefined(typeof(RecipientTypeDetails), CS$ < > 8__locals1.userType))
            {
                throw new EnumArgumentException("userType");
            }
            CS$ < > 8__locals1.cachedServerUseLicense = null;
            if (!PropertyError.IsPropertyNotFound(CS$ < > 8__locals1.sourceAttachment.TryGetProperty(AttachmentSchema.DRMServerLicenseCompressed)))
            {
                using (Stream stream = CS$ < > 8__locals1.sourceAttachment.OpenPropertyStream(AttachmentSchema.DRMServerLicenseCompressed, PropertyOpenMode.ReadOnly))
                {
                    CS$ < > 8__locals1.cachedServerUseLicense = DrmEmailCompression.DecompressUseLicense(stream);
                }
            }
            StreamAttachment.< > c__DisplayClass2 CS$ < > 8__locals2 = CS$ < > 8__locals1;
            int?valueAsNullable = CS$ < > 8__locals1.sourceAttachment.PropertyBag.GetValueAsNullable <int>(AttachmentSchema.DRMRights);

            CS$ < > 8__locals2.cachedUsageRights       = ((valueAsNullable != null) ? new ContentRight?((ContentRight)valueAsNullable.GetValueOrDefault()) : null);
            CS$ < > 8__locals1.cachedExpiryTime        = CS$ < > 8__locals1.sourceAttachment.PropertyBag.GetValueAsNullable <ExDateTime>(AttachmentSchema.DRMExpiryTime);
            CS$ < > 8__locals1.cachedDrmPropsSignature = CS$ < > 8__locals1.sourceAttachment.PropertyBag.GetValueOrDefault <byte[]>(AttachmentSchema.DRMPropsSignature);
            CS$ < > 8__locals1.item = CS$ < > 8__locals1.sourceAttachment.CoreAttachment.ParentCollection.ContainerItem;
            if (string.IsNullOrEmpty(CS$ < > 8__locals1.cachedServerUseLicense) || CS$ < > 8__locals1.cachedUsageRights == null || CS$ < > 8__locals1.cachedExpiryTime == null || CS$ < > 8__locals1.cachedDrmPropsSignature == null)
            {
                string valueOrDefault = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <string>(StoreObjectSchema.ItemClass, string.Empty);
                if (ObjectClass.IsMessage(valueOrDefault, false))
                {
                    CS$ < > 8__locals1.cachedServerUseLicense = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <string>(MessageItemSchema.DRMServerLicense, string.Empty);
                    StreamAttachment.< > c__DisplayClass2 CS$ < > 8__locals3 = CS$ < > 8__locals1;
                    int?valueAsNullable2 = CS$ < > 8__locals1.item.PropertyBag.GetValueAsNullable <int>(MessageItemSchema.DRMRights);
                    CS$ < > 8__locals3.cachedUsageRights       = ((valueAsNullable2 != null) ? new ContentRight?((ContentRight)valueAsNullable2.GetValueOrDefault()) : null);
                    CS$ < > 8__locals1.cachedExpiryTime        = CS$ < > 8__locals1.item.PropertyBag.GetValueAsNullable <ExDateTime>(MessageItemSchema.DRMExpiryTime);
                    CS$ < > 8__locals1.cachedDrmPropsSignature = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <byte[]>(MessageItemSchema.DRMPropsSignature);
                }
            }
            CS$ < > 8__locals1.unprotectionSuccess      = false;
            CS$ < > 8__locals1.useLicenseAndUsageRights = null;
            CS$ < > 8__locals1.validCachedLicense       = false;
            Stream unprotectedAttachment;

            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                StreamAttachment.< > c__DisplayClass4 CS$ < > 8__locals4 = new StreamAttachment.< > c__DisplayClass4();
                CS$ < > 8__locals4.unprotectedAttachment = disposeGuard.Add <Stream>(Streams.CreateTemporaryStorageStream());
                CS$ < > 8__locals4.decryptorHandle       = null;
                using (Stream inputStream = CS$ < > 8__locals1.sourceAttachment.GetContentStream(PropertyOpenMode.ReadOnly))
                {
                    try
                    {
                        MsgToRpMsgConverter.CallRM(delegate
                        {
                            CS$ < > 8__locals1.unprotectionSuccess = ProtectorsManager.Instance.Unprotect(delegate(string protectedDocumentIssuanceLicense)
                            {
                                string valueOrDefault2 = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <string>(ItemSchema.InternetMessageId, string.Empty);
                                bool flag = string.IsNullOrEmpty(valueOrDefault2);
                                RmsClientManagerContext context = new RmsClientManagerContext(CS$ < > 8__locals1.orgId, flag ? RmsClientManagerContext.ContextId.AttachmentFileName : RmsClientManagerContext.ContextId.MessageId, flag ? CS$ < > 8__locals1.sourceAttachment.FileName : valueOrDefault2, null);
                                if (!string.IsNullOrEmpty(CS$ < > 8__locals1.cachedServerUseLicense) && CS$ < > 8__locals1.cachedUsageRights != null && CS$ < > 8__locals1.cachedExpiryTime != null && CS$ < > 8__locals1.cachedDrmPropsSignature != null)
                                {
                                    try
                                    {
                                        CS$ < > 8__locals4.decryptorHandle    = RmsClientManager.VerifyDRMPropsSignatureAndGetDecryptor(context, CS$ < > 8__locals1.userSid, CS$ < > 8__locals1.userType, CS$ < > 8__locals1.userIdentity, CS$ < > 8__locals1.cachedUsageRights.Value, CS$ < > 8__locals1.cachedExpiryTime.Value, CS$ < > 8__locals1.cachedDrmPropsSignature, CS$ < > 8__locals1.cachedServerUseLicense, protectedDocumentIssuanceLicense, UsageRightsSignatureVerificationOptions.LookupSidHistory, StreamAttachment.EmptySidList);
                                        CS$ < > 8__locals1.validCachedLicense = true;
                                        Uri licensingUri = null;
                                        XmlNode[] array  = null;
                                        bool flag2;
                                        RmsClientManager.GetLicensingUri(CS$ < > 8__locals1.orgId, protectedDocumentIssuanceLicense, out licensingUri, out array, out flag2);
                                        CS$ < > 8__locals1.useLicenseAndUsageRights = new UseLicenseAndUsageRights(CS$ < > 8__locals1.cachedServerUseLicense, CS$ < > 8__locals1.cachedUsageRights.Value, CS$ < > 8__locals1.cachedExpiryTime.Value, CS$ < > 8__locals1.cachedDrmPropsSignature, CS$ < > 8__locals1.orgId, protectedDocumentIssuanceLicense, licensingUri);
                                    }
                                    catch (BadDRMPropsSignatureException)
                                    {
                                    }
                                }
                                if (CS$ < > 8__locals1.useLicenseAndUsageRights == null)
                                {
                                    CS$ < > 8__locals1.useLicenseAndUsageRights = RmsClientManager.AcquireUseLicenseAndUsageRights(context, protectedDocumentIssuanceLicense, CS$ < > 8__locals1.userIdentity, CS$ < > 8__locals1.userSid, CS$ < > 8__locals1.userType);
                                    if (CS$ < > 8__locals4.decryptorHandle != null)
                                    {
                                        CS$ < > 8__locals4.decryptorHandle.Close();
                                        CS$ < > 8__locals4.decryptorHandle = null;
                                    }
                                    RmsClientManager.BindUseLicenseForDecryption(context, CS$ < > 8__locals1.useLicenseAndUsageRights.LicensingUri, CS$ < > 8__locals1.useLicenseAndUsageRights.UseLicense, CS$ < > 8__locals1.useLicenseAndUsageRights.PublishingLicense, out CS$ < > 8__locals4.decryptorHandle);
                                }
                                return(CS$ < > 8__locals4.decryptorHandle);
                            }, CS$ < > 8__locals1.sourceAttachment.FileName, inputStream, CS$ < > 8__locals4.unprotectedAttachment);
                        }, ServerStrings.FailedToUnprotectAttachment(CS$ < > 8__locals1.sourceAttachment.FileName));
                    }
Exemple #19
0
        public static IAsyncResult BeginAcquireServerInfo(RmsClientManagerContext context, Uri licenseUri, object state, AsyncCallback callback)
        {
            RmsServerInfoManager.ThrowIfNotInitialized();
            ArgumentValidator.ThrowIfNull("licenseUri", licenseUri);
            AcquireServerInfoAsyncResult acquireServerInfoAsyncResult = new AcquireServerInfoAsyncResult(context, licenseUri, state, callback);

            acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.BeginAcquireServerInfo);
            ExternalRMSServerInfo externalRMSServerInfo;

            if (RmsServerInfoManager.serverInfoMap.TryGet(licenseUri, out externalRMSServerInfo))
            {
                acquireServerInfoAsyncResult.InvokeCallback();
                return(acquireServerInfoAsyncResult);
            }
            RmsClientManagerLog.LogUriEvent(RmsClientManagerLog.RmsClientManagerFeature.ServerInfo, RmsClientManagerLog.RmsClientManagerEvent.Acquire, context, licenseUri);
            WebProxy localServerProxy;

            try
            {
                localServerProxy = RmsClientManagerUtils.GetLocalServerProxy(true);
            }
            catch (ExchangeConfigurationException value)
            {
                acquireServerInfoAsyncResult.InvokeCallback(value);
                return(acquireServerInfoAsyncResult);
            }
            bool flag = RmsServerInfoManager.outstandingFindServiceLocationCalls.EnqueueResult(licenseUri, acquireServerInfoAsyncResult);

            if (flag)
            {
                acquireServerInfoAsyncResult.ServerWSManager = new ServerWSManager(licenseUri, RmsServerInfoManager.perfCounters, acquireServerInfoAsyncResult.LatencyTracker, localServerProxy, RmsClientManager.AppSettings.RmsSoapQueriesTimeout);
                ServiceType[] serviceTypes = new ServiceType[]
                {
                    ServiceType.CertificationWSService,
                    ServiceType.ServerLicensingWSService,
                    ServiceType.CertificationMexService,
                    ServiceType.ServerLicensingMexService
                };
                RmsClientManager.TracePass(null, context.SystemProbeId, "Querying the RMS server {0} for server info", new object[]
                {
                    licenseUri
                });
                acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.BeginFindServiceLocationsFirstRequest);
                try
                {
                    acquireServerInfoAsyncResult.ServerWSManager.BeginFindServiceLocations(serviceTypes, RmsClientManagerUtils.WrapCallbackWithUnhandledExceptionHandlerAndUpdatePoisonContext(new AsyncCallback(RmsServerInfoManager.AcquireServiceLocationCallback)), acquireServerInfoAsyncResult);
                    return(acquireServerInfoAsyncResult);
                }
                catch (InvalidOperationException ex)
                {
                    RmsClientManager.TraceFail(null, context.SystemProbeId, "Hit an exception during BeginFindServiceLocations {0}", new object[]
                    {
                        ex
                    });
                    acquireServerInfoAsyncResult.InvokeCallback(new RightsManagementException(RightsManagementFailureCode.FindServiceLocationFailed, ServerStrings.FailedToFindServerInfo(licenseUri), ex));
                    return(acquireServerInfoAsyncResult);
                }
            }
            RmsClientManager.TracePass(null, context.SystemProbeId, "A request for server info for the license uri {0} is already pending. Enqueuing the result", new object[]
            {
                licenseUri
            });
            acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.BeginFindServiceLocationsPendingRequest);
            return(acquireServerInfoAsyncResult);
        }
Exemple #20
0
        private static void AcquireCertificationMexCallback(ICancelableAsyncResult asyncResult)
        {
            RmsServerInfoManager.Tracer.TraceDebug(0L, "AcquireCertificationMexCallback invoked");
            ArgumentValidator.ThrowIfNull("asyncResult", asyncResult);
            ArgumentValidator.ThrowIfNull("asyncResult.AsyncState", asyncResult.AsyncState);
            AcquireServerInfoAsyncResult acquireServerInfoAsyncResult = asyncResult.AsyncState as AcquireServerInfoAsyncResult;

            if (acquireServerInfoAsyncResult == null)
            {
                throw new InvalidOperationException("asyncResult.AsyncState has to be type of AcquireServerInfoAsyncResult.");
            }
            acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.AcquireCertificationMexCallback);
            Exception ex = null;

            try
            {
                DownloadResult downloadResult = acquireServerInfoAsyncResult.HttpClient.EndDownload(asyncResult);
                acquireServerInfoAsyncResult.LatencyTracker.EndTrackRmsLatency(RmsOperationType.AcquireCertificationMexData);
                if (downloadResult.IsSucceeded)
                {
                    Uri targetUriFromResponse = RmsClientManagerUtils.GetTargetUriFromResponse(downloadResult.ResponseStream);
                    if (targetUriFromResponse == null)
                    {
                        ex = new RightsManagementException(RightsManagementFailureCode.FailedToExtractTargetUriFromMex, ServerStrings.FailedToFindTargetUriFromMExData(acquireServerInfoAsyncResult.CertificationMExUri), acquireServerInfoAsyncResult.LicenseUri.ToString());
                    }
                    else
                    {
                        acquireServerInfoAsyncResult.ServerInfo.CertificationWSTargetUri = TokenTarget.Fix(targetUriFromResponse);
                        acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.BeginDownloadServerLicensingMexData);
                        WebProxy localServerProxy;
                        try
                        {
                            localServerProxy = RmsClientManagerUtils.GetLocalServerProxy(true);
                        }
                        catch (ExchangeConfigurationException ex2)
                        {
                            ex = ex2;
                            return;
                        }
                        HttpSessionConfig httpSessionConfig = new HttpSessionConfig();
                        if (localServerProxy != null)
                        {
                            httpSessionConfig.Proxy = localServerProxy;
                        }
                        acquireServerInfoAsyncResult.LatencyTracker.BeginTrackRmsLatency(RmsOperationType.AcquireServerLicensingMexData);
                        acquireServerInfoAsyncResult.HttpClient.BeginDownload(acquireServerInfoAsyncResult.ServerLicensingMExUri, httpSessionConfig, RmsClientManagerUtils.WrapCancellableCallbackWithUnhandledExceptionHandlerAndUpdatePoisonContext(new CancelableAsyncCallback(RmsServerInfoManager.AcquireServerLicensingMexCallback)), acquireServerInfoAsyncResult);
                    }
                }
                else
                {
                    RmsClientManager.TraceFail(null, acquireServerInfoAsyncResult.Context.SystemProbeId, "Failed to download data from certification MEx {0}.  Exception is {1}", new object[]
                    {
                        acquireServerInfoAsyncResult.CertificationMExUri,
                        downloadResult.Exception
                    });
                    ex = new RightsManagementException(RightsManagementFailureCode.FailedToDownloadMexData, ServerStrings.FailedToDownloadCertificationMExData(downloadResult.ResponseUri), downloadResult.Exception, acquireServerInfoAsyncResult.LicenseUri.ToString());
                    ((RightsManagementException)ex).IsPermanent = !downloadResult.IsRetryable;
                }
            }
            finally
            {
                if (ex != null)
                {
                    acquireServerInfoAsyncResult.Release();
                    RmsServerInfoManager.Tracer.TraceDebug(0L, "AcquireServiceLocationCallback: Invoking find service location callbacks");
                    RmsServerInfoManager.outstandingFindServiceLocationCalls.InvokeCallbacks(acquireServerInfoAsyncResult.LicenseUri, ex);
                }
            }
        }
Exemple #21
0
        private static void AcquireServiceLocationCallback(IAsyncResult asyncResult)
        {
            RmsServerInfoManager.Tracer.TraceDebug(0L, "AcquireServiceLocationCallback invoked");
            ArgumentValidator.ThrowIfNull("asyncResult", asyncResult);
            ArgumentValidator.ThrowIfNull("asyncResult.AsyncState", asyncResult.AsyncState);
            AcquireServerInfoAsyncResult acquireServerInfoAsyncResult = asyncResult.AsyncState as AcquireServerInfoAsyncResult;

            if (acquireServerInfoAsyncResult == null)
            {
                throw new InvalidOperationException("asyncResult.AsyncState has to be type of AcquireServerInfoAsyncResult.");
            }
            acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.AcquireServiceLocationCallback);
            Exception ex = null;

            try
            {
                acquireServerInfoAsyncResult.ServiceLocationResponses = acquireServerInfoAsyncResult.ServerWSManager.EndFindServiceLocations(asyncResult);
                LocalizedString value;
                if (!RmsServerInfoManager.ValidateResponsesAndUpdateServerInfo(acquireServerInfoAsyncResult, out value))
                {
                    ex = new RightsManagementException(RightsManagementFailureCode.FindServiceLocationFailed, ServerStrings.ValidationForServiceLocationResponseFailed(acquireServerInfoAsyncResult.LicenseUri, value));
                }
                else
                {
                    HttpSessionConfig httpSessionConfig = new HttpSessionConfig();
                    WebProxy          localServerProxy  = RmsClientManagerUtils.GetLocalServerProxy(true);
                    if (localServerProxy != null)
                    {
                        httpSessionConfig.Proxy = localServerProxy;
                    }
                    acquireServerInfoAsyncResult.HttpClient = new HttpClient();
                    acquireServerInfoAsyncResult.AddBreadCrumb(Constants.State.BeginDownloadCertificationMexData);
                    acquireServerInfoAsyncResult.LatencyTracker.BeginTrackRmsLatency(RmsOperationType.AcquireCertificationMexData);
                    acquireServerInfoAsyncResult.HttpClient.BeginDownload(acquireServerInfoAsyncResult.CertificationMExUri, httpSessionConfig, RmsClientManagerUtils.WrapCancellableCallbackWithUnhandledExceptionHandlerAndUpdatePoisonContext(new CancelableAsyncCallback(RmsServerInfoManager.AcquireCertificationMexCallback)), acquireServerInfoAsyncResult);
                }
            }
            catch (RightsManagementException ex2)
            {
                RmsClientManager.TraceFail(null, acquireServerInfoAsyncResult.Context.SystemProbeId, "Hit an exception during AcquireServiceLocationCallback {0}", new object[]
                {
                    ex2
                });
                ex = ex2;
            }
            catch (ExchangeConfigurationException ex3)
            {
                RmsClientManager.TraceFail(null, acquireServerInfoAsyncResult.Context.SystemProbeId, "Hit an exception during AcquireServiceLocationCallback {0}", new object[]
                {
                    ex3
                });
                ex = ex3;
            }
            finally
            {
                if (ex != null)
                {
                    acquireServerInfoAsyncResult.Release();
                    RmsServerInfoManager.Tracer.TraceError(0L, "AcquireServiceLocationCallback: Invoking find service location callbacks");
                    RmsServerInfoManager.outstandingFindServiceLocationCalls.InvokeCallbacks(acquireServerInfoAsyncResult.LicenseUri, ex);
                }
            }
        }
        private bool TryCalculateIrmBodyTag(StoreDriverDeliveryEventArgsImpl argsImpl)
        {
            MessageItem messageItem = null;
            bool        result;

            try
            {
                OrganizationId organizationId = argsImpl.ADRecipientCache.OrganizationId;
                MessageItem    replayItem     = argsImpl.ReplayItem;
                using (Attachment attachment = this.TryOpenFirstAttachment(replayItem))
                {
                    StreamAttachmentBase streamAttachmentBase = attachment as StreamAttachmentBase;
                    if (streamAttachmentBase == null)
                    {
                        ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "message.rpmsg attachment is not of the correct type");
                        return(false);
                    }
                    using (Stream contentStream = streamAttachmentBase.GetContentStream(PropertyOpenMode.ReadOnly))
                    {
                        if (contentStream == null)
                        {
                            ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "The rights protected message is not properly formatted");
                            return(false);
                        }
                        using (DrmEmailMessageContainer drmEmailMessageContainer = new DrmEmailMessageContainer())
                        {
                            try
                            {
                                drmEmailMessageContainer.Load(contentStream, (object param0) => Streams.CreateTemporaryStorageStream());
                            }
                            catch (InvalidRpmsgFormatException)
                            {
                                ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "The rights protected message is not properly formatted");
                                return(false);
                            }
                            string text = null;
                            if (!argsImpl.MailItemDeliver.MbxTransportMailItem.ExtendedProperties.TryGetValue <string>("Microsoft.Exchange.RightsManagement.TransportDecryptionUL", out text) || string.IsNullOrEmpty(text))
                            {
                                ConversationsProcessingAgent.tracer.TraceError((long)this.GetHashCode(), "Failed to load the useLicense");
                                return(false);
                            }
                            try
                            {
                                Uri       licenseUri;
                                XmlNode[] array;
                                bool      flag;
                                RmsClientManager.GetLicensingUri(organizationId, drmEmailMessageContainer.PublishLicense, out licenseUri, out array, out flag);
                                RpMsgToMsgConverter     rpMsgToMsgConverter = new RpMsgToMsgConverter(drmEmailMessageContainer, organizationId, false);
                                RmsClientManagerContext context             = new RmsClientManagerContext(organizationId, RmsClientManagerContext.ContextId.MessageId, replayItem.InternetMessageId, argsImpl.ADRecipientCache, new RmsLatencyTracker(argsImpl.MailItemDeliver.MbxTransportMailItem.LatencyTracker), drmEmailMessageContainer.PublishLicense);
                                using (DisposableTenantLicensePair disposableTenantLicensePair = RmsClientManager.AcquireTenantLicenses(context, licenseUri))
                                {
                                    messageItem = rpMsgToMsgConverter.ConvertRpmsgToMsg(replayItem, text, disposableTenantLicensePair.EnablingPrincipalRac);
                                }
                            }
                            catch (RightsManagementException arg)
                            {
                                ConversationsProcessingAgent.tracer.TraceError <RightsManagementException>((long)this.GetHashCode(), "Conversion failed: {0}", arg);
                                return(false);
                            }
                            catch (InvalidRpmsgFormatException arg2)
                            {
                                ConversationsProcessingAgent.tracer.TraceError <InvalidRpmsgFormatException>((long)this.GetHashCode(), "Conversion failed: {0}", arg2);
                                return(false);
                            }
                            catch (ExchangeConfigurationException arg3)
                            {
                                ConversationsProcessingAgent.tracer.TraceError <ExchangeConfigurationException>((long)this.GetHashCode(), "Conversion failed: {0}", arg3);
                                return(false);
                            }
                            catch (AttachmentProtectionException arg4)
                            {
                                ConversationsProcessingAgent.tracer.TraceError <AttachmentProtectionException>((long)this.GetHashCode(), "Conversion failed: {0}", arg4);
                                return(false);
                            }
                        }
                    }
                }
                this.bodyTag = messageItem.Body.CalculateBodyTag(out this.latestMessageWordCount);
                if (messageItem.AttachmentCollection.Count == 0)
                {
                    this.forceAllAttachmentsHidden = true;
                }
                else
                {
                    foreach (AttachmentHandle attachmentHandle in messageItem.AttachmentCollection)
                    {
                        if (!attachmentHandle.IsInline)
                        {
                            break;
                        }
                        this.forceAllAttachmentsHidden = true;
                    }
                }
                result = true;
            }
            finally
            {
                if (messageItem != null)
                {
                    messageItem.Dispose();
                }
            }
            return(result);
        }