protected override void PostDeserialize() { if (!base.EvaluationContext.IsMachineLevel && !PartialTrustHelpers.IsInFullTrust()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.Runtime.Serialization.SR.GetString("ConfigDataContractSerializerSectionLoadError"))); } }
// IsCacheUnderPressure is part of a DOS mitigation mechanism addressing CSDMain#195148. Original problem: when a large number of // HTTP requests for WSDL or the ASMX documentation page is made, each request with a unique value of the HOST header, a unique response // is generated and cached for each of the requests (responses contain the scheme/host/port of the request). // This leads to ever growing memory consumption and eventual crash of the process. // The mitigation for this DOS attack uses the following mechanism: // 1. The behavior of the system remains unchanged for the first 10 requests for WSDL of a given ASMX service that have differing // scheme/host/port combination of the request URI. This is to avoid breaking behavioral changes in the 99.99% case, // since the DOS attack cannot be generically fixed without breaking behavioral changes. The value of 10 is baked in, // and we consider it a reasonable default based on the assumption that ASMX services in most circumstances cannot be // reached using more than 10 different values of the scheme/host/port. // 2. For any requests for WSDL going beyond the 10 limit of scheme/host/port combination, we go into a “DOS mitigation mode”. // The mode prevents the eventual process crash while introducing marginal breaking behavioral changes: // a. We create a single service description and cache it using the AbsolutePath of the request URI alone // (as opposed to scheme/host/port + AbsolutePath). // b. For every request for WSDL/disco/documentation document, we fix up the URLs in the returned document to match the // scheme/host/port of the actual request for WSDL/disco. This fixup only applies to the WSDL extensions we have shipped in .NET // and does not apply to custom extensions implemented externally, hence the breaking behavioral change. // This mechamism affects the DiscoveryServerProtocol and DocumentationServerProtocol. internal bool IsCacheUnderPressure(Type protocolType, Type serverType) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); const int threshold = 10; string key = this.CreateKey(protocolType, serverType, true, "CachePressure"); ServerProtocolCachePressure item = (ServerProtocolCachePressure)HttpRuntime.Cache.Get(key); // There is a potential race condition in creating a new entry or increasing the value of an existing entry, // but it is acceptable since DOS threshold enforcement need not be exact. if (item != null) { return(item.Pressure < threshold?Interlocked.Increment(ref item.Pressure) >= threshold : false); } else { HttpRuntime.Cache.Insert( key, new ServerProtocolCachePressure { Pressure = 1 }, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); return(false); } }
public static Exception PrepareForRethrow(this Exception exception) { Fx.Assert(exception != null, "The specified Exception is null."); if (!ShouldPrepareForRethrow(exception)) { return(exception); } if (PartialTrustHelpers.UnsafeIsInFullTrust()) { // Racing here is harmless if (ExceptionExtensions.prepForRemotingMethodInfo == null) { #if WINDOWS_UWP || PCL || NETSTANDARD1_3 // No Type.GetMethod in UWP nor NetStandard1.3 ExceptionExtensions.prepForRemotingMethodInfo = null; #else ExceptionExtensions.prepForRemotingMethodInfo = typeof(Exception).GetMethod("PrepForRemoting", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { }, new ParameterModifier[] { }); #endif } if (ExceptionExtensions.prepForRemotingMethodInfo != null) { // PrepForRemoting is not thread-safe. When the same exception instance is thrown by multiple threads // the remote stack trace string may not format correctly. However, We don't lock this to protect us from it given // it is discouraged to throw the same exception instance from multiple threads and the side impact is ignorable. prepForRemotingMethodInfo.Invoke(exception, new object[] { }); } } return(exception); }
static CreateCustomKeyForAspNetWebServiceMetadataCache GetCreateCustomKeyForAspNetWebServiceMetadataCacheDelegate(Type serverType) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); string key = "CreateCustomKeyForAspNetWebServiceMetadataCache-" + serverType.FullName; CreateCustomKeyForAspNetWebServiceMetadataCache result = (CreateCustomKeyForAspNetWebServiceMetadataCache)HttpRuntime.Cache.Get(key); if (result == null) { MethodInfo createKeyMethod = serverType.GetMethod( "CreateCustomKeyForAspNetWebServiceMetadataCache", BindingFlags.Public | BindingFlags.Static | BindingFlags.ExactBinding | BindingFlags.FlattenHierarchy, null, new Type[] { typeof(Type), typeof(Type), typeof(string) }, null); if (createKeyMethod == null) { result = ServerProtocol.DefaultCreateCustomKeyForAspNetWebServiceMetadataCache; } else { result = delegate(Type pt, Type st, string originalString) { return((string)createKeyMethod.Invoke(null, new object[] { pt, st, originalString })); }; } HttpRuntime.Cache.Add(key, result, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } return(result); }
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); base.DeserializeElement(reader, serializeCollectionKey); // Update paths // If we're not running in the context of a web application then skip this setting. #if MONO_BROKEN_CONFIGURATION_DLL try { var hack = this.EvaluationContext; } catch (ConfigurationErrorsException) { this.actualPath = GetConfigurationDirectory(); return; } #endif ContextInformation context = this.EvaluationContext; WebContext webContext = context.HostingContext as WebContext; if (webContext == null) { return; } if (this.Href.Length == 0) { return; } string tempVirtualPath = webContext.Path; string path = null; // If the help page is not in the web app directory hierarchy (the case // for those specified in machine.config like DefaultWsdlHelpGenerator.aspx) // then we can't construct a true virtual path. This means that certain web // form features that rely on relative paths won't work. if (tempVirtualPath == null) { tempVirtualPath = HostingEnvironment.ApplicationVirtualPath; if (tempVirtualPath == null) { tempVirtualPath = ""; } path = GetConfigurationDirectory(); } else { path = HostingEnvironment.MapPath(tempVirtualPath); } if (!tempVirtualPath.EndsWith("/", StringComparison.Ordinal)) { tempVirtualPath += "/"; } CheckIOReadPermission(path, this.Href); this.actualPath = path; this.virtualPath = tempVirtualPath; this.needToValidateHref = true; }
private HttpContext SwitchContext(HttpContext context) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); HttpContext oldContext = HttpContext.Current; HttpContext.Current = context; return(oldContext); }
static EtwDiagnosticTrace() { // In Partial Trust, initialize to Guid.Empty to disable ETW Tracing. if (!PartialTrustHelpers.HasEtwPermissions()) { defaultEtwProviderId = Guid.Empty; } }
internal void SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); this.type = type; this.context = context; this.request = request; this.response = response; Initialize(); }
// See comment on the ServerProtocol.IsCacheUnderPressure method for explanation of the excludeSchemeHostPort logic. internal void AddToCache(Type protocolType, Type serverType, object value, bool excludeSchemeHostPort) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); HttpRuntime.Cache.Insert(CreateKey(protocolType, serverType, excludeSchemeHostPort), value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); }
static WebServicesSection GetConfigFromHttpContext() { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); HttpContext context = HttpContext.Current; if (context != null) { return((WebServicesSection)context.GetSection(WebServicesSection.SectionName)); } return(null); }
static EtwDiagnosticTrace() { EtwDiagnosticTrace.ImmutableDefaultEtwProviderId = new Guid("{c651f5f6-1c0d-492e-8ae1-b4efd7c9d503}"); EtwDiagnosticTrace.defaultEtwProviderId = EtwDiagnosticTrace.ImmutableDefaultEtwProviderId; EtwDiagnosticTrace.etwProviderCache = new Hashtable(); EtwDiagnosticTrace.isVistaOrGreater = Environment.OSVersion.Version.Major >= 6; EtwDiagnosticTrace.transferEventDescriptor = new EventDescriptor(0x1f3, 0, 18, 0, 0, 0, 0x20000000001a0065L); if (!PartialTrustHelpers.HasEtwPermissions()) { EtwDiagnosticTrace.defaultEtwProviderId = Guid.Empty; } }
protected override void PostDeserialize() { // Perf optimization. If the configuration is coming from machine.config // It is safe and we don't need to check for permissions. if (EvaluationContext.IsMachineLevel) { return; } if (!PartialTrustHelpers.IsInFullTrust()) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigDataContractSerializerSectionLoadError))); } }
protected override void Reset(ConfigurationElement parentElement) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); WsdlHelpGeneratorElement parent = (WsdlHelpGeneratorElement)parentElement; #if MONO_BROKEN_CONFIGURATION_DLL try { var hack = this.EvaluationContext; } catch (ConfigurationErrorsException) { base.Reset(parentElement); this.actualPath = GetConfigurationDirectory(); return; } #endif ContextInformation context = this.EvaluationContext; WebContext webContext = context.HostingContext as WebContext; if (webContext != null) { string tempVirtualPath = webContext.Path; bool isMachineConfig = tempVirtualPath == null; this.actualPath = parent.actualPath; if (isMachineConfig) { tempVirtualPath = HostingEnvironment.ApplicationVirtualPath; } if ((tempVirtualPath != null) && !tempVirtualPath.EndsWith("/", StringComparison.Ordinal)) { tempVirtualPath += "/"; } if ((tempVirtualPath == null) && (parentElement != null)) { this.virtualPath = parent.virtualPath; } else if (tempVirtualPath != null) { this.virtualPath = tempVirtualPath; } } base.Reset(parentElement); }
internal static object CreateImplementation(Type serviceType) { ConstructorInfo constructor = serviceType.GetConstructor( TypeLoader.DefaultBindingFlags, null, Type.EmptyTypes, null); if (constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.SFxNoDefaultConstructor))); } // Stop the partially trusted callers to use the ServiceDescription.GetService(Type) method to // instantiate types in this assembly that are not public or have a non-public default constructor. if ((!PartialTrustHelpers.AppDomainFullyTrusted) && (serviceType.IsNotPublic || (!constructor.IsPublic)) && (serviceType.Assembly == typeof(ServiceDescription).Assembly)) { PartialTrustHelpers.DemandForFullTrust(); } try { object implementation = constructor.Invoke( TypeLoader.DefaultBindingFlags, null, null, System.Globalization.CultureInfo.InvariantCulture); return(implementation); } catch (MethodAccessException methodAccessException) { SecurityException securityException = methodAccessException.InnerException as SecurityException; if (securityException != null && securityException.PermissionType.Equals(typeof(ReflectionPermission))) { DiagnosticUtility.TraceHandledException(methodAccessException, TraceEventType.Warning); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustServiceCtorNotVisible, serviceType.FullName))); } else { throw; } } }
internal void SetDefaults() { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); HttpContext context = HttpContext.Current; if (context != null) { this.virtualPath = HostingEnvironment.ApplicationVirtualPath; } this.actualPath = this.GetConfigurationDirectory(); if ((this.virtualPath != null) && (!this.virtualPath.EndsWith("/", StringComparison.Ordinal))) { this.virtualPath += "/"; } if ((this.actualPath != null) && (!this.actualPath.EndsWith(@"\", StringComparison.Ordinal))) { this.actualPath += "\\"; } this.Href = "DefaultWsdlHelpGenerator.aspx"; CheckIOReadPermission(this.actualPath, this.Href); this.needToValidateHref = true; }
protected override void Reset(ConfigurationElement parentElement) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); WsdlHelpGeneratorElement parent = (WsdlHelpGeneratorElement)parentElement; ContextInformation context = this.EvaluationContext; WebContext webContext = context.HostingContext as WebContext; if (webContext != null) { string tempVirtualPath = webContext.Path; bool isMachineConfig = tempVirtualPath == null; this.actualPath = parent.actualPath; if (isMachineConfig) { tempVirtualPath = HostingEnvironment.ApplicationVirtualPath; } if ((tempVirtualPath != null) && !tempVirtualPath.EndsWith("/", StringComparison.Ordinal)) { tempVirtualPath += "/"; } if ((tempVirtualPath == null) && (parentElement != null)) { this.virtualPath = parent.virtualPath; } else if (tempVirtualPath != null) { this.virtualPath = tempVirtualPath; } } base.Reset(parentElement); }
internal object GetFromCache(Type protocolType, Type serverType, bool excludeSchemeHostPort) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); return(HttpRuntime.Cache.Get(CreateKey(protocolType, serverType, excludeSchemeHostPort))); }
string GetConfigurationDirectory() { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); return(HttpRuntime.MachineConfigurationDirectory); }