public void LogCertificate(EdgeSyncLoggingLevel level, EdgeSyncEvent logEvent, X509Certificate2 cert) { if (cert == null) { return; } if (!this.CanLogEvent(level)) { return; } this.LogEvent(level, logEvent, cert.Subject, "Certificate subject"); this.LogEvent(level, logEvent, cert.IssuerName.Name, "Certificate issuer name"); this.LogEvent(level, logEvent, cert.SerialNumber, "Certificate serial number"); this.LogEvent(level, logEvent, cert.Thumbprint, "Certificate thumbprint"); StringBuilder stringBuilder = new StringBuilder(256); foreach (string value in TlsCertificateInfo.GetFQDNs(cert)) { if (stringBuilder.Length != 0) { stringBuilder.Append(';'); } stringBuilder.Append(value); } this.LogEvent(level, logEvent, stringBuilder.ToString(), "Certificate alternate names"); }
internal static void ValidateCertificate(ExchangeCertificate certificate, bool skipAutomatedDeploymentChecks) { ExchangeCertificateValidity exchangeCertificateValidity = ManageExchangeCertificate.ValidateExchangeCertificate(certificate, true); if (exchangeCertificateValidity != ExchangeCertificateValidity.Valid) { throw new FederationCertificateInvalidException(Strings.CertificateNotValidForExchange(certificate.Thumbprint, exchangeCertificateValidity.ToString())); } if (string.IsNullOrEmpty(certificate.SubjectKeyIdentifier)) { throw new FederationCertificateInvalidException(Strings.ErrorCertificateNoSKI(certificate.Thumbprint)); } if (!skipAutomatedDeploymentChecks && !certificate.PrivateKeyExportable) { throw new FederationCertificateInvalidException(Strings.ErrorCertificateNotExportable(certificate.Thumbprint)); } if (!string.Equals(certificate.GetKeyAlgorithm(), WellKnownOid.RsaRsa.Value, StringComparison.OrdinalIgnoreCase)) { throw new FederationCertificateInvalidException(Strings.ErrorCertificateNotRSA(certificate.Thumbprint)); } if (TlsCertificateInfo.IsCNGProvider(certificate)) { throw new FederationCertificateInvalidException(Strings.ErrorCertificateNotCAPI(certificate.Thumbprint)); } if ((ExDateTime)certificate.NotAfter < ExDateTime.UtcNow && (ExDateTime)certificate.NotBefore > ExDateTime.UtcNow) { throw new FederationCertificateInvalidException(Strings.ErrorCertificateHasExpired(certificate.Thumbprint)); } }
private void GetRpsCertificateThumbprint() { if (this.isCasServer) { Exception ex = null; try { ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 614, "GetRpsCertificateThumbprint", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\Monitoring\\Tasks\\TestRemotePowerShellConnectivity.cs"); ServiceEndpoint endpoint = topologyConfigurationSession.GetEndpointContainer().GetEndpoint("ForwardSyncRpsEndPoint"); this.certThumbprint = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(endpoint.CertificateSubject).Thumbprint; } catch (ServiceEndpointNotFoundException ex2) { ex = ex2; } catch (ArgumentException ex3) { ex = ex3; } if (ex != null) { this.monitoringData.Events.Add(new MonitoringEvent("MSExchange Monitoring PowerShellConnectivity External", 1012, EventTypeEnumeration.Warning, "PS ExternalUrl test for certificate connection skipped:" + ex.ToString())); } } }
private DNSWebSvcClient OpenDnsServiceClient() { DNSWebSvcClient dnswebSvcClient = new DNSWebSvcClient(this.wsb, new EndpointAddress(this.endpointUrl, new AddressHeader[0])); dnswebSvcClient.ClientCredentials.ClientCertificate.Certificate = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(this.authorizationCertificateSubject); dnswebSvcClient.Open(); return(dnswebSvcClient); }
private static X509Certificate2 GetDefaultCertificate() { string[] names = new string[] { ComputerInformation.DnsFullyQualifiedDomainName, ComputerInformation.DnsHostName, ComputerInformation.DnsPhysicalFullyQualifiedDomainName, ComputerInformation.DnsPhysicalHostName }; return(TlsCertificateInfo.FindCertificate(names, CertificateSelectionOption.PreferedNonSelfSigned)); }
private static void ReEncryptEdgeSyncCredentials(Server server, X509Certificate2 oldCertificate, X509Certificate2 newCertificate) { if (server.EdgeSyncCredentials == null || server.EdgeSyncCredentials.Count == 0) { return; } if (oldCertificate == null) { throw new InvalidOperationException(Strings.InternalTransportCertificateCorruptedInADOnHub); } if (TlsCertificateInfo.IsCNGProvider(newCertificate)) { throw new InvalidOperationException(Strings.InternalTransportCertificateMustBeCAPICertificate(newCertificate.Thumbprint)); } oldCertificate = ExchangeCertificate.GetCertificateFromStore(StoreName.My, oldCertificate.Thumbprint); if (oldCertificate == null) { throw new InvalidOperationException(Strings.InternalTransportCertificateCorruptedInADOnHub); } EdgeSyncCredential[] array = new EdgeSyncCredential[server.EdgeSyncCredentials.Count]; using (RSACryptoServiceProvider rsacryptoServiceProvider = (RSACryptoServiceProvider)oldCertificate.PrivateKey) { for (int i = 0; i < server.EdgeSyncCredentials.Count; i++) { array[i] = EdgeSyncCredential.DeserializeEdgeSyncCredential(server.EdgeSyncCredentials[i]); try { array[i].EncryptedESRAPassword = rsacryptoServiceProvider.Decrypt(array[i].EncryptedESRAPassword, false); } catch (CryptographicException) { throw new InvalidOperationException(Strings.InternalTransportCertificateCorruptedInADOnHub); } } } using (RSACryptoServiceProvider rsacryptoServiceProvider2 = newCertificate.PublicKey.Key as RSACryptoServiceProvider) { if (rsacryptoServiceProvider2 != null) { for (int j = 0; j < array.Length; j++) { if (array[j].EncryptedESRAPassword != null) { array[j].EncryptedESRAPassword = rsacryptoServiceProvider2.Encrypt(array[j].EncryptedESRAPassword, false); server.EdgeSyncCredentials[j] = EdgeSyncCredential.SerializeEdgeSyncCredential(array[j]); } } } } }
// Token: 0x06000CA0 RID: 3232 RVA: 0x00038B1C File Offset: 0x00036D1C internal ServiceProxyPool(WSHttpBinding binding, ServiceEndpoint serviceEndpoint) { this.pool = new ConcurrentQueue <T>(); this.channelFactory = new ChannelFactory <T>(binding, serviceEndpoint.Uri.ToString()); try { this.channelFactory.Credentials.ClientCertificate.Certificate = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(serviceEndpoint.CertificateSubject); } catch (ArgumentException ex) { throw new GlsPermanentException(DirectoryStrings.PermanentGlsError(ex.Message)); } ServicePointManager.DefaultConnectionLimit = Math.Max(ServicePointManager.DefaultConnectionLimit, 8 * Environment.ProcessorCount); }
private static void EnsureInitialized() { if (Util.IsMicrosoftHostedOnly && NavBarClientBase.endPointConfiguration == null) { NavBarClientBase.endPointConfiguration = ConfigurationManager.AppSettings["ShellServiceEndPointConfiguration"]; NavBarClientBase.showPerfConsole = StringComparer.OrdinalIgnoreCase.Equals("true", WebConfigurationManager.AppSettings["ShowPerformanceConsole"]); NavBarClientBase.certificateSubject = ConfigurationManager.AppSettings["MsOnlineShellService_CertSubject"]; NavBarClientBase.certificateThumbprint = ConfigurationManager.AppSettings["MsOnlineShellService_CertThumbprint"]; string text = string.Format("{0}{1}/scripts/o365shared.js", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion); string theme = ((PagesSection)ConfigurationManager.GetSection("system.web/pages")).Theme; string text2 = string.Format("{0}{1}/themes/{2}/o365shared.css", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion, theme); string text3 = string.Format("{0}{1}/themes/{2}/o365shared-rtl.css", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion, theme); string text4 = string.Format("{0}{1}/themes/{2}/o365shared.png", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion, theme); string text5 = string.Format("{0}{1}/scripts/CoreShellBundle.js", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion); string text6 = string.Format("{0}{1}/themes/{2}/O365ShellCore.css", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion, theme); string text7 = string.Format("{0}{1}/themes/{2}/O365ShellCore-rtl.css", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion, theme); string text8 = string.Format("{0}{1}/scripts/O365ShellPlusTestExtension.js", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion); string text9 = string.Format("{0}{1}/themes/{2}/O365ShellPlus.css", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion, theme); string text10 = string.Format("{0}{1}/themes/{2}/O365ShellPlus-rtl.css", EcpUrl.EcpVDirForStaticResource, Util.ApplicationVersion, theme); string text11 = ConfigurationManager.AppSettings["O365Url"]; MockNavBar.Initialize(text11, text, text2, text3, text4, text5, text6, text7, text8, text9, text10); if (NavBarClientBase.endPointConfiguration != null && !string.IsNullOrEmpty(NavBarClientBase.certificateThumbprint)) { NavBarClientBase.certificate = TlsCertificateInfo.FindCertByThumbprint(NavBarClientBase.certificateThumbprint); NavBarClientBase.loadConfigSuccess = (NavBarClientBase.certificate != null); } ExTraceGlobals.WebServiceTracer.TraceInformation(0, 0L, "NavBarHelper load config success: {0}. EndPointConfiguration: '{1}'; ShellJs: '{2}'; Certicate: '{3}' {4}.", new object[] { NavBarClientBase.loadConfigSuccess, NavBarClientBase.endPointConfiguration, text, NavBarClientBase.certificateSubject, (NavBarClientBase.certificate != null) ? "found" : "not found" }); if (!NavBarClientBase.loadConfigSuccess) { EcpEventLogConstants.Tuple_Office365NavBarLoadConfigFailed.LogEvent(new object[] { NavBarClientBase.loadConfigSuccess, NavBarClientBase.endPointConfiguration, text, NavBarClientBase.certificateSubject }); } } }
protected override DirectorySyncClient CreateService() { ServiceEndpoint serviceEndpoint = null; try { serviceEndpoint = MsoSyncService.GetMsoEndpoint(); } catch (Exception innerException) { throw new CouldNotCreateMsoSyncServiceException(Strings.CouldNotGetMsoEndpoint, innerException); } DirectorySyncClient result; try { EndpointAddress remoteAddress = new EndpointAddress(serviceEndpoint.Uri, new AddressHeader[0]); result = new DirectorySyncClient(new WSHttpBinding(SecurityMode.Transport) { Security = { Transport = { ClientCredentialType = HttpClientCredentialType.Certificate } }, MaxBufferPoolSize = 5242880L, MaxReceivedMessageSize = 5242880L }, remoteAddress) { ClientCredentials = { ClientCertificate = { Certificate = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(serviceEndpoint.CertificateSubject) } } }; } catch (Exception ex) { throw new CouldNotCreateMsoSyncServiceException(ex.Message, ex); } return(result); }
protected override void InternalProcessRecord() { TaskLogger.LogEnter(); WebSvcDns webSvcDns = new WebSvcDns(null, ""); DNSWebSvcClient dnswebSvcClient = null; AcceptedDomain dataObject = this.DataObject; string domain = dataObject.DomainName.Domain; try { dnswebSvcClient = new DNSWebSvcClient(webSvcDns.Wsb, new EndpointAddress(this.dnsEndpoint, new AddressHeader[0])); dnswebSvcClient.ClientCredentials.ClientCertificate.Certificate = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(this.certificateSubject); dnswebSvcClient.Open(); if (dnswebSvcClient.IsDomainAvailable(domain)) { return; } ResourceRecord[] allResourceRecordsByDomainName = dnswebSvcClient.GetAllResourceRecordsByDomainName(domain); foreach (ResourceRecord record in allResourceRecordsByDomainName) { base.WriteObject(new WebDnsRecord(record)); } } catch (TimeoutException exception) { base.WriteError(exception, ErrorCategory.InvalidArgument, dataObject); } catch (SecurityAccessDeniedException exception2) { base.WriteError(exception2, ErrorCategory.InvalidArgument, dataObject); } catch (CommunicationException exception3) { base.WriteError(exception3, ErrorCategory.InvalidArgument, dataObject); } finally { if (dnswebSvcClient != null) { dnswebSvcClient.Close(); } } TaskLogger.LogExit(); }
// Token: 0x06000B45 RID: 2885 RVA: 0x00033B28 File Offset: 0x00031D28 private static ChannelFactory <TClient> CreateChannelFactory(string endpointName, ServiceEndpoint serviceEndpoint, Binding defaultBinding, Trace tracer) { ArgumentValidator.ThrowIfNull("endpointName", endpointName); ArgumentValidator.ThrowIfNull("serviceEndpoint", serviceEndpoint); ArgumentValidator.ThrowIfNull("defaultBinding", defaultBinding); ArgumentValidator.ThrowIfNull("tracer", tracer); ChannelFactory <TClient> channelFactory = null; try { channelFactory = WcfUtils.TryCreateChannelFactoryFromConfig <TClient>(endpointName); } catch (Exception ex) { tracer.TraceError <string, string>(0L, "ServiceProxyPool - Error Creating channel factory from config file for {0}. Details {1}", endpointName, ex.ToString()); Globals.LogEvent(DirectoryEventLogConstants.Tuple_WcfClientConfigError, endpointName, new object[] { endpointName, ex.Message }); } if (channelFactory == null) { channelFactory = new ChannelFactory <TClient>(defaultBinding, serviceEndpoint.Uri.ToString()); } WSHttpBinding wshttpBinding = defaultBinding as WSHttpBinding; if (wshttpBinding != null && wshttpBinding.Security.Transport.ClientCredentialType == HttpClientCredentialType.Certificate) { try { channelFactory.Credentials.ClientCertificate.Certificate = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(serviceEndpoint.CertificateSubject); } catch (ArgumentException ex2) { throw new GlsPermanentException(DirectoryStrings.PermanentGlsError(ex2.Message)); } } DirectoryServiceProxyPool <TClient> .ConfigWCFServicePointManager(); return(channelFactory); }
private static bool CertificateHasLowerPrecedence(X509Store store, ChainEngine engine, string fqdn, X509Certificate2 certificate, out X509Certificate2 best) { CertificateSelectionOption options = CertificateSelectionOption.WildcardAllowed | CertificateSelectionOption.PreferedNonSelfSigned; string[] names = new string[] { fqdn }; IEnumerable <X509Certificate2> enumerable = TlsCertificateInfo.FindAll(store, names, options, engine, out best); bool flag = false; foreach (X509Certificate2 x509Certificate in enumerable) { if (string.Equals(certificate.Thumbprint, x509Certificate.Thumbprint, StringComparison.OrdinalIgnoreCase)) { flag = true; break; } } return(flag && best != null && !string.Equals(best.Thumbprint, certificate.Thumbprint, StringComparison.OrdinalIgnoreCase)); }
protected override void InternalValidate() { bool flag = false; try { this.localServer = ManageExchangeCertificate.FindLocalServer((ITopologyConfigurationSession)this.ConfigurationSession); } catch (LocalServerNotFoundException) { flag = true; } if (flag || !ManageExchangeCertificate.IsServerRoleSupported(this.localServer)) { base.WriteError(new RoleDoesNotSupportExchangeCertificateTasksException(), ErrorCategory.InvalidOperation, null); } ManageExchangeCertificate.AddUniqueDomainIfValid(this.rawDomains, ComputerInformation.DnsHostName); ManageExchangeCertificate.AddUniqueDomainIfValid(this.rawDomains, ComputerInformation.DnsPhysicalHostName); ManageExchangeCertificate.AddUniqueDomainIfValid(this.rawDomains, ComputerInformation.DnsFullyQualifiedDomainName); ManageExchangeCertificate.AddUniqueDomainIfValid(this.rawDomains, ComputerInformation.DnsPhysicalFullyQualifiedDomainName); this.subjectName = TlsCertificateInfo.GetDefaultSubjectName(this.rawDomains); }
private static void SetPopImapCertificate(X509Certificate2 cert, PopImapAdConfiguration popImapAdConfiguration, IConfigurationSession dataSession, List <LocalizedString> warningList) { if (popImapAdConfiguration != null) { IList <string> fqdns = TlsCertificateInfo.GetFQDNs(cert); if (fqdns.Count == 0) { return; } popImapAdConfiguration.X509CertificateName = fqdns[0]; try { dataSession.Save(popImapAdConfiguration); } catch (DataValidationException) { if (warningList != null) { warningList.Add(Strings.WarnInvalidCertificateForProtocol(cert.Thumbprint, fqdns[0], popImapAdConfiguration.ProtocolName.Remove(popImapAdConfiguration.ProtocolName.Length - 1))); } } } }
internal static ExchangeCertificateValidity CheckCNGSettings(X509Certificate2 certificate) { string providerName; string keyName; TlsCertificateInfo.GetProviderInfo(certificate, out providerName, out keyName); SafeNCryptHandle safeNCryptHandle; int num = CngNativeMethods.NCryptOpenStorageProvider(out safeNCryptHandle, providerName, 0U); if (num != 0) { throw new CryptographicException(num); } using (safeNCryptHandle) { uint valueSize = (uint)Marshal.SizeOf(typeof(uint)); uint num2; uint num3; num = CngNativeMethods.NCryptGetProperty(safeNCryptHandle, "Impl Type", out num2, valueSize, out num3, (CngNativeMethods.PropertyOptions) 0U); if (num != 0) { throw new CryptographicException(num); } CngNativeMethods.ImplemenationType implemenationType = (CngNativeMethods.ImplemenationType)num2; if ((implemenationType & CngNativeMethods.ImplemenationType.Hardware) == CngNativeMethods.ImplemenationType.Hardware && (implemenationType & CngNativeMethods.ImplemenationType.Removable) == CngNativeMethods.ImplemenationType.Removable) { return(ExchangeCertificateValidity.CspKeyContainerInfoRemovableDevice); } CngNativeMethods.KeyOptions options = CngNativeMethods.KeyOptions.MachineKeyset | CngNativeMethods.KeyOptions.Silent; SafeNCryptHandle safeNCryptHandle3; num = CngNativeMethods.NCryptOpenKey(safeNCryptHandle, out safeNCryptHandle3, keyName, 0U, options); if (num != 0) { if (num == -2146893802) { return(ExchangeCertificateValidity.PrivateKeyNotAccessible); } if (num == -2146893790) { return(ExchangeCertificateValidity.CspKeyContainerInfoProtected); } throw new CryptographicException(num); } else { using (safeNCryptHandle3) { num = CngNativeMethods.NCryptGetProperty(safeNCryptHandle3, "Length", out num2, valueSize, out num3, (CngNativeMethods.PropertyOptions) 0U); if (num != 0) { throw new CryptographicException(num); } if (num2 < 1024U) { return(ExchangeCertificateValidity.PublicKeyUnsupportedSize); } } } } return(ExchangeCertificateValidity.Valid); }
protected override void InternalProcessRecord() { X509Certificate2 x509Certificate = null; if (!string.IsNullOrEmpty(this.thumbprint)) { this.thumbprint = ManageExchangeCertificate.UnifyThumbprintFormat(this.thumbprint); x509Certificate = this.FindCertificate(this.thumbprint); if (x509Certificate == null) { base.WriteError(new ArgumentException(Strings.CertificateNotFound(this.thumbprint), "Thumbprint"), ErrorCategory.InvalidArgument, this.thumbprint); } } else { AllowedServices allowedServices = this.Services; if (allowedServices != AllowedServices.IIS && allowedServices != (AllowedServices.IMAP | AllowedServices.POP | AllowedServices.IIS)) { if (allowedServices != AllowedServices.SMTP) { return; } } else { x509Certificate = this.FindIisCertificate(); } if (x509Certificate == null && this.Services != AllowedServices.SMTP) { try { x509Certificate = InstallExchangeCertificate.GetDefaultCertificate(); } catch (ArgumentException exception) { base.WriteError(exception, ErrorCategory.InvalidData, null); return; } } if (x509Certificate == null) { if (!this.rawDomains.Any <string>()) { base.WriteError(new UnableToResolveValidDomainExchangeCertificateTasksException(ComputerInformation.DnsHostName, ComputerInformation.DnsPhysicalHostName, ComputerInformation.DnsFullyQualifiedDomainName, ComputerInformation.DnsPhysicalFullyQualifiedDomainName), ErrorCategory.InvalidOperation, null); } try { x509Certificate = this.GenerateSelfSignedCertificate(); } catch (CryptographicException exception2) { base.WriteError(exception2, ErrorCategory.InvalidOperation, null); } } if (x509Certificate != null && this.InstallInTrustedRootCAIfSelfSigned && TlsCertificateInfo.IsSelfSignedCertificate(x509Certificate)) { TlsCertificateInfo.TryInstallCertificateInTrustedRootCA(x509Certificate); } } base.WriteVerbose(Strings.CertificateInformation(x509Certificate.Issuer, x509Certificate.NotBefore, x509Certificate.NotAfter, x509Certificate.Subject)); if ((DateTime)ExDateTime.Now < x509Certificate.NotBefore || (DateTime)ExDateTime.Now > x509Certificate.NotAfter) { base.WriteError(new CryptographicException(Strings.CertificateStatusDateInvalid), ErrorCategory.InvalidData, null); } try { this.EnableForServices(x509Certificate, this.Services); } catch (IISNotInstalledException) { base.WriteError(new ArgumentException(Strings.IISNotInstalled, "Services"), ErrorCategory.InvalidArgument, null); } catch (InvalidOperationException exception3) { base.WriteError(exception3, ErrorCategory.ObjectNotFound, null); } }
protected X509Certificate2 GenerateSelfSignedCertificate() { TimeSpan validFor = DateTime.UtcNow.AddMonths(60) - DateTime.UtcNow; return(TlsCertificateInfo.CreateSelfSignCertificate(this.subjectName, this.rawDomains, validFor, CertificateCreationOption.None, 2048, null)); }
// Token: 0x06000369 RID: 873 RVA: 0x0000D608 File Offset: 0x0000B808 private void InvokeBposShellService(AuthZClientInfo effectiveCaller) { string text = string.Empty; try { using (ShellServiceClient shellServiceClient = new ShellServiceClient("MsOnlineShellService_EndPointConfiguration")) { string certificateThumbprint = ConfigurationManager.AppSettings["MsOnlineShellService_CertThumbprint"]; shellServiceClient.ClientCredentials.ClientCertificate.Certificate = TlsCertificateInfo.FindCertByThumbprint(certificateThumbprint); EndpointAddress address = shellServiceClient.Endpoint.Address; Uri uri = new Uri(address.Uri.AbsoluteUri); shellServiceClient.Endpoint.Address = new EndpointAddress(uri, address.Identity, new AddressHeader[0]); string text2 = HttpContext.Current.Request.Headers["RPSOrgIdPUID"]; this.userPuid = (string.IsNullOrEmpty(text2) ? HttpContext.Current.Request.Headers["RPSPUID"] : text2); this.boxServiceUrl = shellServiceClient.Endpoint.Address.Uri.AbsoluteUri; text = Guid.NewGuid().ToString(); OwaApplication.GetRequestDetailsLogger.ActivityScope.SetProperty(BposAssetReader <T> .LogMetadata.ShellRequestInfo, string.Format("OP:{0},UP:{1},UPN:{2},G:{3}", new object[] { text2, this.userPuid, this.userPrincipalName, text })); this.data = this.ExecuteRequest(shellServiceClient, this.culture.Name, this.userPrincipalName, this.userPuid, effectiveCaller, text); this.LogWorkloadLinks(this.data); } } catch (Exception e) { this.data = default(T); this.LogExceptionFromBposShellService(e, text); } }
// Token: 0x06001A94 RID: 6804 RVA: 0x000634DC File Offset: 0x000616DC protected override Alert[] InternalExecute() { string text = HttpContext.Current.Request.Headers["RPSOrgIdPUID"]; string userPuid = string.IsNullOrEmpty(text) ? HttpContext.Current.Request.Headers["RPSPUID"] : text; string principalName = ((LiveIDIdentity)Thread.CurrentPrincipal.Identity).PrincipalName; string shellServiceUrl = string.Empty; string trackingGuid = Guid.NewGuid().ToString(); Alert[] alerts; try { using (ShellServiceClient shellServiceClient = new ShellServiceClient("MsOnlineShellService_EndPointConfiguration")) { string certificateThumbprint = ConfigurationManager.AppSettings["MsOnlineShellService_CertThumbprint"]; shellServiceClient.ClientCredentials.ClientCertificate.Certificate = TlsCertificateInfo.FindCertByThumbprint(certificateThumbprint); shellServiceUrl = shellServiceClient.Endpoint.Address.Uri.AbsoluteUri; GetAlertRequest getAlertRequest = new GetAlertRequest { WorkloadId = WorkloadAuthenticationId.Exchange, UserPuid = userPuid, UserPrincipalName = principalName, TrackingGuid = trackingGuid, CultureName = Thread.CurrentThread.CurrentUICulture.Name }; alerts = shellServiceClient.GetAlerts(getAlertRequest); } } catch (Exception) { this.LogExceptionFromO365ShellService(principalName, userPuid, shellServiceUrl, trackingGuid); throw; } return(alerts); }
internal static ExchangeCertificateValidity ValidateExchangeCertificate(X509Certificate2 cert, bool ignoreAccessible) { if (cert == null) { throw new ArgumentNullException("cert"); } if (!cert.HasPrivateKey) { return(ExchangeCertificateValidity.PrivateKeyMissing); } string keyAlgorithm = cert.GetKeyAlgorithm(); bool flag = string.Equals(keyAlgorithm, WellKnownOid.X957Sha1Dsa.Value, StringComparison.OrdinalIgnoreCase); if (!string.Equals(keyAlgorithm, WellKnownOid.RsaRsa.Value, StringComparison.OrdinalIgnoreCase) && !flag) { return(ExchangeCertificateValidity.KeyAlgorithmUnsupported); } foreach (X509Extension x509Extension in cert.Extensions) { try { X509KeyUsageExtension x509KeyUsageExtension = x509Extension as X509KeyUsageExtension; if (x509KeyUsageExtension != null) { X509KeyUsageFlags keyUsages = x509KeyUsageExtension.KeyUsages; bool flag2 = false; if (keyUsages == X509KeyUsageFlags.None) { flag2 = true; } else if ((keyUsages & (X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.DigitalSignature)) != X509KeyUsageFlags.None) { flag2 = true; } if (!flag2) { return(ExchangeCertificateValidity.SigningNotSupported); } } } catch (CryptographicException) { return(ExchangeCertificateValidity.KeyUsageCorrupted); } try { X509EnhancedKeyUsageExtension x509EnhancedKeyUsageExtension = x509Extension as X509EnhancedKeyUsageExtension; if (x509EnhancedKeyUsageExtension != null && x509EnhancedKeyUsageExtension.EnhancedKeyUsages.Count > 0 && x509EnhancedKeyUsageExtension.EnhancedKeyUsages[WellKnownOid.PkixKpServerAuth.Value] == null) { return(ExchangeCertificateValidity.PkixKpServerAuthNotFoundInEnhancedKeyUsage); } } catch (CryptographicException) { return(ExchangeCertificateValidity.EnhancedKeyUsageCorrupted); } } if (TlsCertificateInfo.IsCNGProvider(cert)) { return(ManageExchangeCertificate.CheckCNGSettings(cert)); } AsymmetricAlgorithm privateKey; try { privateKey = cert.PrivateKey; } catch (CryptographicException) { return(ExchangeCertificateValidity.PrivateKeyNotAccessible); } ICspAsymmetricAlgorithm cspAsymmetricAlgorithm = privateKey as ICspAsymmetricAlgorithm; if (cspAsymmetricAlgorithm == null) { return(ExchangeCertificateValidity.PrivateKeyUnsupportedAlgorithm); } CspKeyContainerInfo cspKeyContainerInfo = cspAsymmetricAlgorithm.CspKeyContainerInfo; if (cspKeyContainerInfo.Protected) { return(ExchangeCertificateValidity.CspKeyContainerInfoProtected); } if (cspKeyContainerInfo.HardwareDevice && cspKeyContainerInfo.Removable) { return(ExchangeCertificateValidity.CspKeyContainerInfoRemovableDevice); } if (!ignoreAccessible && !cspKeyContainerInfo.Accessible) { return(ExchangeCertificateValidity.CspKeyContainerInfoNotAccessible); } switch (cspKeyContainerInfo.KeyNumber) { case KeyNumber.Exchange: case KeyNumber.Signature: { AsymmetricAlgorithm key = cert.PublicKey.Key; if (key.KeySize < 1024) { return(ExchangeCertificateValidity.PublicKeyUnsupportedSize); } return(ExchangeCertificateValidity.Valid); } default: return(ExchangeCertificateValidity.CspKeyContainerInfoUnknownKeyNumber); } }
private void GetSuiteServiceInfo() { if (this.suiteServiceProxyInfo == null) { string text = HttpContext.Current.Request.Headers["RPSOrgIdPUID"]; string userPuid = string.IsNullOrEmpty(text) ? HttpContext.Current.Request.Headers["RPSPUID"] : text; string principalName = ((LiveIDIdentity)Thread.CurrentPrincipal.Identity).PrincipalName; string shellServiceUrl = string.Empty; string trackingGuid = string.Empty; try { using (ShellServiceClient shellServiceClient = new ShellServiceClient("MsOnlineShellService_EndPointConfiguration")) { string certificateThumbprint = ConfigurationManager.AppSettings["MsOnlineShellService_CertThumbprint"]; shellServiceClient.ClientCredentials.ClientCertificate.Certificate = TlsCertificateInfo.FindCertByThumbprint(certificateThumbprint); shellServiceUrl = shellServiceClient.Endpoint.Address.Uri.AbsoluteUri; trackingGuid = Guid.NewGuid().ToString(); GetSuiteServiceInfoRequest getSuiteServiceInfoRequest = new GetSuiteServiceInfoRequest { WorkloadId = WorkloadAuthenticationId.Exchange, CultureName = CultureInfo.CurrentUICulture.Name, UserPuid = userPuid, UserPrincipalName = principalName, TrackingGuid = trackingGuid, UrlOfRequestingPage = HttpContext.Current.Request.QueryString["returnUrl"] }; this.suiteServiceProxyInfo = shellServiceClient.GetSuiteServiceInfo(getSuiteServiceInfoRequest); } } catch (Exception exception) { this.suiteServiceProxyInfo = null; this.LogExceptionFromO365ShellService(exception, principalName, userPuid, shellServiceUrl); } } }
// Token: 0x06001BCF RID: 7119 RVA: 0x0006B438 File Offset: 0x00069638 private bool UpdateO365Theme(string themeId, string userPrincipalName, UserContext userContext) { bool flag = userContext.FeaturesManager.ClientServerSettings.O365Header.Enabled || userContext.FeaturesManager.ClientServerSettings.O365G2Header.Enabled; this.tracer.TraceDebug <bool, bool>(0L, "UpdateO365Theme::isFeatureSupported='{0}', this.skipO365Call='{1}'", flag, this.request.SkipO365Call); if (!flag || this.request.SkipO365Call) { return(false); } string text = null; string text2 = null; string text3 = string.Empty; bool result; try { using (ShellServiceClient shellServiceClient = new ShellServiceClient("MsOnlineShellService_EndPointConfiguration")) { string text4 = ConfigurationManager.AppSettings["MsOnlineShellService_CertThumbprint"]; this.tracer.TraceDebug <string, CommunicationState>(1L, "UpdateO365Theme::certificateThumbprint='{0}',client.State'={1}'", text4, shellServiceClient.State); shellServiceClient.ClientCredentials.ClientCertificate.Certificate = TlsCertificateInfo.FindCertByThumbprint(text4); EndpointAddress address = shellServiceClient.Endpoint.Address; Uri uri = new Uri(address.Uri.AbsoluteUri); shellServiceClient.Endpoint.Address = new EndpointAddress(uri, address.Identity, new AddressHeader[0]); string text5 = HttpContext.Current.Request.Headers["RPSOrgIdPUID"]; text = (string.IsNullOrEmpty(text5) ? HttpContext.Current.Request.Headers["RPSPUID"] : text5); text2 = shellServiceClient.Endpoint.Address.Uri.AbsoluteUri; text3 = Guid.NewGuid().ToString(); this.tracer.TraceDebug(2L, "UpdateO365Theme::orgIdPuid='{0}', userPuid='{1}', userPrincipalName='{2}',serviceUrl='{3}'", new object[] { text5, text, userPrincipalName, text2 }); SetUserThemeRequest setUserThemeRequest = new SetUserThemeRequest { ThemeId = themeId, TrackingGuid = text3, UserPrincipalName = userPrincipalName, UserPuid = text, WorkloadId = WorkloadAuthenticationId.Exchange }; this.tracer.TraceDebug(3L, "UpdateO365Theme::setUserThemeRequest.ThemeId='{0}', .TrackingGuid='{1}', .UserPrincipalName='{2}', .UserPuid='{3}', .WorkloadId='{4}'", new object[] { setUserThemeRequest.ThemeId, setUserThemeRequest.TrackingGuid, setUserThemeRequest.UserPrincipalName, setUserThemeRequest.UserPuid, setUserThemeRequest.WorkloadId }); shellServiceClient.SetUserTheme(setUserThemeRequest); this.tracer.TraceDebug <CommunicationState>(4L, "UpdateO365Theme::setUserThemeRequest.State='{0}'", shellServiceClient.State); result = true; } } catch (Exception ex) { this.tracer.TraceError(5L, "UpdateO365Theme::Exception: themeId='{0}', trackingGuid='{1}', userPrincipalName='{2}', userPuid='{3}', serviceUrl='{4}', exception='{5}'", new object[] { themeId, text3, userPrincipalName, text, text2, ex }); OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_O365SetUserThemeError, userPrincipalName + text2 + themeId, new object[] { text, userPrincipalName, text3, text2, themeId, ex }); result = false; } return(result); }
public static IMailboxReplicationProxyService CreateChannel(MailboxReplicationProxyClient proxyClient) { ChannelFactory <IMailboxReplicationProxyService> channelFactory = proxyClient.ChannelFactory; EndpointAddress address = proxyClient.Endpoint.Address; if (address.Uri != null && (address.Uri.Scheme == Uri.UriSchemeHttps || address.Uri.Scheme == Uri.UriSchemeHttp)) { if (!ExchangeSessionAwareClientsHelper.webRequestCreator.IsDisabled) { UriBuilder uriBuilder = new UriBuilder(address.Uri); uriBuilder.Path = proxyClient.RequestContext.Id.ToString(); if (proxyClient.UseCertificateToAuthenticate) { string config = ConfigBase <MRSConfigSchema> .GetConfig <string>("ProxyClientCertificateSubject"); try { channelFactory.Credentials.ClientCertificate.Certificate = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(config, false); } catch (ArgumentException ex) { throw new CertificateLoadErrorException(config, ex.Message, ex); } } return(channelFactory.CreateChannel(address, uriBuilder.Uri)); } CustomBinding customBinding = channelFactory.Endpoint.Binding as CustomBinding; if (customBinding != null) { HttpsTransportBindingElement httpsTransportBindingElement = customBinding.Elements.Find <HttpsTransportBindingElement>(); if (httpsTransportBindingElement != null) { httpsTransportBindingElement.AllowCookies = true; } } } return(channelFactory.CreateChannel(address)); }
internal static Dictionary <AllowedServices, LocalizedString> EnableForServices(X509Certificate2 cert, AllowedServices services, string websiteName, bool requireSsl, ITopologyConfigurationSession dataSession, Server server, List <LocalizedString> warningList, bool allowConfirmation, bool forceNetworkService) { Dictionary <AllowedServices, LocalizedString> dictionary = new Dictionary <AllowedServices, LocalizedString>(3); if (dataSession == null) { throw new ArgumentNullException("dataSession"); } if (server == null) { throw new ArgumentNullException("server"); } if ((services & AllowedServices.IIS) != AllowedServices.None) { if (allowConfirmation && !IisUtility.SslRequiredOnTheRoot(null) && requireSsl) { dictionary[AllowedServices.IIS] = Strings.ConfirmEnforceRequireSslOnRoot; } else { IisUtility.SetSslCertificateByName(websiteName, cert, requireSsl); } } if ((services & AllowedServices.POP) != AllowedServices.None || (services & AllowedServices.IMAP) != AllowedServices.None || (services & AllowedServices.SMTP) != AllowedServices.None || forceNetworkService) { AccessRule rule = new CryptoKeyAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null), CryptoKeyRights.GenericRead, AccessControlType.Allow); try { TlsCertificateInfo.AddAccessRule(cert, rule); } catch (CryptographicException innerException) { throw new AddAccessRuleCryptographicException(cert.Thumbprint, innerException); } catch (ArgumentException innerException2) { throw new AddAccessRuleArgumentException(cert.Thumbprint, innerException2); } catch (UnauthorizedAccessException innerException3) { throw new AddAccessRuleUnauthorizedAccessException(cert.Thumbprint, innerException3); } catch (COMException innerException4) { throw new AddAccessRuleCOMException(cert.Thumbprint, innerException4); } } if ((services & AllowedServices.SMTP) != AllowedServices.None) { ManageExchangeCertificate.WarnIfNotBestMatch(new ExchangeCertificate(cert), dataSession, server, warningList); LocalizedString localizedString = ManageExchangeCertificate.UpdateActiveDirectory(cert, dataSession, server, warningList, allowConfirmation); if (localizedString != LocalizedString.Empty) { dictionary[AllowedServices.SMTP] = localizedString; } } if ((services & AllowedServices.POP) != AllowedServices.None) { ManageExchangeCertificate.SetPop3Certificate(cert, dataSession, warningList); } if ((services & AllowedServices.IMAP) != AllowedServices.None) { ManageExchangeCertificate.SetImap4Certificate(cert, dataSession, warningList); } if ((services & AllowedServices.UM) != AllowedServices.None) { ManageExchangeCertificate.SetUMCertificate(cert, server, dataSession, allowConfirmation, dictionary, warningList); } if ((services & AllowedServices.UMCallRouter) != AllowedServices.None) { ManageExchangeCertificate.SetUMCallRouterCertificate(cert, server, dataSession, allowConfirmation, dictionary, warningList); } if (dictionary.Count <= 0) { return(null); } return(dictionary); }
private void CheckCertificateChainAndCacheProps() { if (this.status != CertificateStatus.Unknown) { return; } if (!string.IsNullOrEmpty(this.CertificateRequest)) { this.status = CertificateStatus.PendingRequest; this.selfSigned = false; this.rootCAType = CertificateAuthorityType.Unknown; return; } this.privateKeyExportable = TlsCertificateInfo.IsCertificateExportable(this); ChainPolicyParameters options = new BaseChainPolicyParameters(ChainPolicyOptions.None); ChainMatchIssuer pkixKpServerAuth = AndChainMatchIssuer.PkixKpServerAuth; ChainBuildParameter parameter = new ChainBuildParameter(pkixKpServerAuth, TimeSpan.FromSeconds(30.0), false, TimeSpan.Zero); using (ChainEngine chainEngine = new ChainEngine()) { using (ChainContext chainContext = chainEngine.Build(this, ChainBuildOptions.CacheEndCert | ChainBuildOptions.RevocationCheckChainExcludeRoot | ChainBuildOptions.RevocationAccumulativeTimeout, parameter)) { if (chainContext == null) { this.status = CertificateStatus.Unknown; this.selfSigned = false; this.rootCAType = CertificateAuthorityType.Unknown; } else { this.selfSigned = chainContext.IsSelfSigned; if (chainContext.Status == TrustStatus.IsUntrustedRoot) { if (chainContext.IsSelfSigned) { this.status = CertificateStatus.Valid; this.rootCAType = CertificateAuthorityType.None; } else { this.status = CertificateStatus.Untrusted; this.rootCAType = CertificateAuthorityType.Unknown; } } else { ChainSummary chainSummary = chainContext.Validate(options); ChainValidityStatus chainValidityStatus = chainSummary.Status; if (chainValidityStatus <= (ChainValidityStatus)2148081683U) { if (chainValidityStatus == ChainValidityStatus.Valid) { this.status = CertificateStatus.Valid; goto IL_168; } switch (chainValidityStatus) { case (ChainValidityStatus)2148081682U: case (ChainValidityStatus)2148081683U: break; default: goto IL_15A; } } else { if (chainValidityStatus == (ChainValidityStatus)2148204801U) { this.status = CertificateStatus.DateInvalid; goto IL_168; } switch (chainValidityStatus) { case (ChainValidityStatus)2148204812U: this.status = CertificateStatus.Revoked; goto IL_168; case (ChainValidityStatus)2148204813U: goto IL_15A; case (ChainValidityStatus)2148204814U: break; default: goto IL_15A; } } this.status = CertificateStatus.RevocationCheckFailure; goto IL_168; IL_15A: this.status = CertificateStatus.Invalid; this.rootCAType = CertificateAuthorityType.Unknown; IL_168: if (this.status != CertificateStatus.Invalid) { X509Certificate2 rootCertificate = chainContext.RootCertificate; if (rootCertificate == null) { throw new InvalidOperationException("Root certificate was null!"); } this.rootCAType = ExchangeCertificate.RootSource(rootCertificate.Thumbprint); } } } } } }
private X509Certificate2 GenerateCertificate() { return(TlsCertificateInfo.CreateSelfSignCertificate(new X500DistinguishedName("CN=" + InstallAuthCertificate.CertificateSubject), null, InstallAuthCertificate.CertificateLifeTime, CertificateCreationOption.Exportable, 2048, InstallAuthCertificate.CertificateSubject)); }