Files
acceptance-tests
data
docs
external
ikvm-native
libgc
llvm
m4
man
mcs
build
class
Accessibility
Commons.Xml.Relaxng
Cscompmgd
CustomMarshalers
Facades
I18N
IBM.Data.DB2
ICSharpCode.SharpZipLib
Microsoft.Build
Microsoft.Build.Engine
Microsoft.Build.Framework
Microsoft.Build.Tasks
Microsoft.Build.Utilities
Microsoft.CSharp
Microsoft.NuGet.Build.Tasks
Microsoft.VisualC
Microsoft.Web.Infrastructure
MicrosoftAjaxLibrary
Mono.Btls.Interface
Mono.C5
Mono.CSharp
Mono.Cairo
Mono.Cecil
Mono.Cecil.Mdb
Mono.CodeContracts
Mono.CompilerServices.SymbolWriter
Mono.Data.Sqlite
Mono.Data.Tds
Mono.Debugger.Soft
Mono.Http
Mono.Management
Mono.Messaging
Mono.Messaging.RabbitMQ
Mono.Options
Mono.Parallel
Mono.Posix
Mono.Profiler.Log
Mono.Runtime.Tests
Mono.Security
Mono.Security.Win32
Mono.Simd
Mono.Tasklets
Mono.WebBrowser
Mono.XBuild.Tasks
Novell.Directory.Ldap
PEAPI
RabbitMQ.Client
SMDiagnostics
System
System.ComponentModel.Composition.4.5
System.ComponentModel.DataAnnotations
System.Configuration
System.Configuration.Install
System.Core
System.Data
System.Data.DataSetExtensions
System.Data.Entity
System.Data.Linq
System.Data.OracleClient
System.Data.Services
System.Data.Services.Client
System.Deployment
System.Design
System.DirectoryServices
System.DirectoryServices.Protocols
System.Drawing
System.Drawing.Design
System.Dynamic
System.EnterpriseServices
System.IO.Compression
System.IO.Compression.FileSystem
System.IdentityModel
System.IdentityModel.Selectors
System.Json
System.Json.Microsoft
System.Management
System.Messaging
System.Net
System.Net.Http
System.Net.Http.Formatting
System.Net.Http.WebRequest
System.Net.Http.WinHttpHandler
System.Numerics
System.Numerics.Vectors
System.Reactive.Core
System.Reactive.Debugger
System.Reactive.Experimental
System.Reactive.Interfaces
System.Reactive.Linq
System.Reactive.Observable.Aliases
System.Reactive.PlatformServices
System.Reactive.Providers
System.Reactive.Runtime.Remoting
System.Reactive.Windows.Forms
System.Reactive.Windows.Threading
System.Reflection.Context
System.Runtime.Caching
System.Runtime.CompilerServices.Unsafe
System.Runtime.DurableInstancing
System.Runtime.Remoting
System.Runtime.Serialization
System.Runtime.Serialization.Formatters.Soap
System.Security
System.ServiceModel
System.ServiceModel.Activation
System.ServiceModel.Discovery
System.ServiceModel.Internals
System.ServiceModel.Routing
System.ServiceModel.Web
System.ServiceProcess
System.Threading.Tasks.Dataflow
System.Transactions
System.Web
System.Web.Abstractions
System.Web.ApplicationServices
System.Web.DynamicData
System.Web.Extensions
System.Web.Extensions.Design
System.Web.Http
System.Web.Http.SelfHost
System.Web.Http.WebHost
System.Web.Mobile
System.Web.Mvc3
System.Web.Razor
System.Web.RegularExpressions
System.Web.Routing
System.Web.Services
System.Web.WebPages
System.Web.WebPages.Deployment
System.Web.WebPages.Razor
System.Windows
System.Windows.Forms
System.Windows.Forms.DataVisualization
System.Workflow.Activities
System.Workflow.ComponentModel
System.Workflow.Runtime
System.XML
System.Xaml
System.Xml.Linq
System.Xml.Serialization
SystemWebTestShim
WebMatrix.Data
WindowsBase
aot-compiler
corlib
dlr
doc
legacy
lib
monodoc
notes
reference-assemblies
referencesource
SMDiagnostics
System
System.Activities
System.Activities.Core.Presentation
System.Activities.DurableInstancing
System.Activities.Presentation
System.ComponentModel.DataAnnotations
System.Configuration
System.Core
System.Data
System.Data.DataSetExtensions
System.Data.Entity
System.Data.Entity.Design
System.Data.Linq
System.Data.SqlXml
System.IdentityModel
System.IdentityModel.Selectors
System.Net
System.Numerics
System.Runtime.Caching
System.Runtime.DurableInstancing
System.Runtime.Serialization
System.ServiceModel
System.ServiceModel.Activation
System.ServiceModel.Activities
System.ServiceModel.Channels
System.ServiceModel.Discovery
System.ServiceModel.Internals
System.ServiceModel.Routing
System.ServiceModel.WasHosting
System.ServiceModel.Web
System.Web
Abstractions
Administration
Cache
Compilation
Configuration
DataAccess
DataAnnotations
Handlers
Hosting
Instrumentation
InternalApis
IntraPartitionAPIs
Management
ModelBinding
Profile
Properties
Routing
Security
State
UI
Util
WebSockets
misc
AspNetEventSource.cs
AspNetSynchronizationContext.cs
AspNetSynchronizationContextBase.cs
BufferAllocator.cs
CachedPathData.cs
CrossSiteScriptingValidation.cs
DefaultHttpHandler.cs
DynamicModuleRegistry.cs
DynamicValidationShim.cs
ErrorFormatter.cs
EtwTrace.cs
EventHandlerTaskAsyncHelper.cs
FileChangesMonitor.cs.REMOVED.git-id
GlobalSuppressions.cs.REMOVED.git-id
GlobalSuppressions2.cs.REMOVED.git-id
GlobalSuppressions3.cs
GlobalSuppressions4.cs
HTTPNotFoundHandler.cs
HtmlString.cs
HttpApplication.cs.REMOVED.git-id
HttpApplicationFactory.cs
HttpAsyncResult.cs
HttpBrowserCapabilities.cs
HttpBufferlessInputStream.cs
HttpCacheParams.cs
HttpCachePolicy.cs
HttpCacheVary.cs
HttpCacheVaryByContentEncodings.cs
HttpChannelBindingToken.cs
HttpClientCertificate.cs
HttpContext.cs
HttpCookie.cs
HttpCookieCollection.cs
HttpDebugHandler.cs
HttpDictionary.cs
HttpException.cs
HttpFileCollection.cs
HttpHeaderCollection.cs
HttpInputStream.cs
HttpModuleCollection.cs
HttpPostedFile.cs
HttpRawResponse.cs
HttpRequest.cs.REMOVED.git-id
HttpResponse.cs.REMOVED.git-id
HttpResponseHeader.cs
HttpRuntime.cs.REMOVED.git-id
HttpServerVarsCollection.cs
HttpTaskAsyncHandler.cs
HttpValueCollection.cs
HttpWriter.cs
IHtmlString.cs
IHttpAsyncHandler.cs
IHttpHandler.cs
IHttpHandlerFactory.cs
IHttpModule.cs
IPrincipalContainer.cs
IRequestCompletedNotifier.cs
ISubscriptionToken.cs
ITlsTokenBindingInfo.cs
IdleTimeoutMonitor.cs
IisTraceListener.cs
ImpersonationContext.cs
ImplicitAsyncPreloadModule.cs
IntSecurity.cs
LegacyAspNetSynchronizationContext.cs
MimeMapping.cs
ModuleConfigurationInfo.cs
ModulesEntry.cs
MultipartContentParser.cs
NativeMethods.cs
NotificationContext.cs
OutputCacheModule.cs
PartitionResolver.cs
PerfCounters.cs
PipelineModuleStepContainer.cs
PreApplicationStartMethodAttribute.cs
ProcessInfo.cs
ProcessModelInfo.cs
ReadEntityBodyMode.cs
RequestNotification.cs
RequestNotificationStatus.cs
RequestQueue.cs
RequestTimeoutManager.cs
RootedObjects.cs
SafeNativeMethods.cs
SiteMap.cs
SiteMapNode.cs
SiteMapNodeCollection.cs
SiteMapProvider.cs
StaticFileHandler.cs
StaticSiteMapProvider.cs
StringResourceManager.cs
System.Web.txt.REMOVED.git-id
TaskAsyncHelper.cs
TaskWrapperAsyncResult.cs
ThreadContext.cs
UnsafeNativeMethods.cs
UnvalidatedRequestValues.cs
UnvalidatedRequestValuesBase.cs
UnvalidatedRequestValuesWrapper.cs
UrlMappingsModule.cs
ValidateStringCallback.cs
VirtualPath.cs
VirtualPathUtility.cs
WebCategoryAttribute.cs
WebPageTraceListener.cs
WebSocketPipeline.cs
WebSocketTransitionState.cs
WebSysDefaultValueAttribute.cs
WebSysDescriptionAttribute.cs
WebSysDisplayNameAttribute.cs
WorkerRequest.cs
XmlSiteMapProvider.cs
cacheexpires.cspp
cacheusage.cspp
httpapplicationstate.cs
httpserverutility.cs
httpstaticobjectscollection.cs
System.Web.ApplicationServices
System.Web.DataVisualization
System.Web.DynamicData
System.Web.Entity
System.Web.Entity.Design
System.Web.Extensions
System.Web.Mobile
System.Web.Routing
System.Web.Services
System.Workflow.Activities
System.Workflow.ComponentModel
System.Workflow.Runtime
System.WorkflowServices
System.Xaml.Hosting
System.Xml
System.Xml.Linq
XamlBuildTask
mscorlib
LICENSE.txt
PATENTS.TXT
README.Mono.md
README.md
test-helpers
LICENSE
Makefile
Open.snk
README
ecma.pub
mono.pub
mono.snk
msfinal.pub
reactive.pub
silverlight.pub
winfx.pub
winfx3.pub
docs
errors
ilasm
jay
mcs
nunit24
packages
tests
tools
AUTHORS
COPYING
INSTALL.txt
Makefile
MonoIcon.png
README
ScalableMonoIcon.svg
mkinstalldirs
mono
msvc
po
runtime
samples
scripts
support
tools
COPYING.LIB
LICENSE
Makefile.am
Makefile.in
NEWS
README.md
acinclude.m4
aclocal.m4
autogen.sh
code_of_conduct.md
compile
config.guess
config.h.in
config.rpath
config.sub
configure.REMOVED.git-id
configure.ac.REMOVED.git-id
depcomp
install-sh
ltmain.sh.REMOVED.git-id
missing
mkinstalldirs
mono-uninstalled.pc.in
test-driver
winconfig.h
linux-packaging-mono/mcs/class/referencesource/System.Web/CrossSiteScriptingValidation.cs
Xamarin Public Jenkins (auto-signing) e79aa3c0ed Imported Upstream version 4.6.0.125
Former-commit-id: a2155e9bd80020e49e72e86c44da02a8ac0e57a4
2016-08-03 10:59:49 +00:00

196 lines
7.3 KiB
C#

//------------------------------------------------------------------------------
// <copyright file="CrossSiteScriptingValidation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Detection of unsafe strings from the client (aee ASURT 122278 for details)
*
*/
namespace System.Web {
using System;
using System.Globalization;
internal static class CrossSiteScriptingValidation {
private static bool IsAtoZ(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
// Per VSWhidbey 362133, we no longer check for those cases
#if OBSOLETE
// Detect strings like "OnFocus="
private static bool IsDangerousOnString(string s, int index) {
// If the next character is not an 'n', it's safe
if (s[index+1] != 'n' && s[index+1] != 'N') return false;
// If the previous character is a letter, it's safe (e.g. "won")
if (index > 0 && IsAtoZ(s[index-1])) return false;
int len = s.Length;
// Skip any number of letters, then any number of white spaces
index += 2;
while (index < len && IsAtoZ(s[index])) index++;
while (index < len && Char.IsWhiteSpace(s[index])) index++;
// If there is an equal, it's unsafe
return (index < len && s[index] == '=');
}
// Detect strings like "javascript:"
private static bool IsDangerousScriptString(string s, int index) {
int len = s.Length;
// Check for end of string case
if (index+6 >= len) return false;
// If the 's' is not followed by "cript", it's safe
// We avoid calling String.Compare for perf reasons.
if ((s[index+1] != 'c' && s[index+1] != 'C') ||
(s[index+2] != 'r' && s[index+2] != 'R') ||
(s[index+3] != 'i' && s[index+3] != 'I') ||
(s[index+4] != 'p' && s[index+4] != 'P') ||
(s[index+5] != 't' && s[index+5] != 'T')) return false;
// Skip any number of white spaces
index += 6;
while (index < len && Char.IsWhiteSpace(s[index])) index++;
// If there is a colon, it's unsafe
return (index < len && s[index] == ':');
}
// Detect "expression(". (as in style="qqq:expression(alert('Attack!'))", see ASURT 127079)
private static bool IsDangerousExpressionString(string s, int index) {
// Check for end of string case
if (index+10 >= s.Length) return false;
// If the 'e' is not followed by an "x", it's safe.
// This avoids calling String.Compare in most cases ("ex?" is rare)
if (s[index+1] != 'x' && s[index+1] != 'X') return false;
// Check the rest of the string
return (String.Compare(
s, index+2, "pression(", 0, 9, true /*ignoreCase*/,
CultureInfo.InvariantCulture) == 0);
}
#endif // OBSOLETE
// Detect constructs that look like HTML tags
#if OBSOLETE
private static char[] startingChars = new char[] { '<', '&', '/', '*', 'o', 'O', 's', 'S' , 'e', 'E' };
#endif // OBSOLETE
private static char[] startingChars = new char[] { '<', '&' };
// Only accepts http: and https: protocols, and protocolless urls.
// Used by web parts to validate import and editor input on Url properties.
// Review: is there a way to escape colon that will still be recognized by IE?
// %3a does not work with IE.
internal static bool IsDangerousUrl(string s) {
if (String.IsNullOrEmpty(s)) {
return false;
}
// Trim the string inside this method, since a Url starting with whitespace
// is not necessarily dangerous. This saves the caller from having to pre-trim
// the argument as well.
s = s.Trim();
int len = s.Length;
if ((len > 4) &&
((s[0] == 'h') || (s[0] == 'H')) &&
((s[1] == 't') || (s[1] == 'T')) &&
((s[2] == 't') || (s[2] == 'T')) &&
((s[3] == 'p') || (s[3] == 'P'))) {
if ((s[4] == ':') ||
((len > 5) && ((s[4] == 's') || (s[4] == 'S')) && (s[5] == ':'))) {
return false;
}
}
int colonPosition = s.IndexOf(':');
if (colonPosition == -1) {
return false;
}
return true;
}
internal static bool IsValidJavascriptId(string id) {
return (String.IsNullOrEmpty(id) || System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(id));
}
internal static bool IsDangerousString(string s, out int matchIndex) {
//bool inComment = false;
matchIndex = 0;
for (int i=0;;) {
// Look for the start of one of our patterns
int n = s.IndexOfAny(startingChars, i);
// If not found, the string is safe
if (n<0) return false;
// If it's the last char, it's safe
if (n == s.Length-1) return false;
matchIndex = n;
switch (s[n]) {
case '<':
// If the < is followed by a letter or '!', it's unsafe (looks like a tag or HTML comment)
if (IsAtoZ(s[n+1]) || s[n+1] == '!' || s[n+1] == '/' || s[n+1] == '?') return true;
break;
case '&':
// If the & is followed by a #, it's unsafe (e.g. &#83;)
if (s[n+1] == '#') return true;
break;
#if OBSOLETE
case '/':
// Look for a starting C style comment (i.e. "/*")
if (s[n+1] == '*') {
// Remember that we're inside a comment
inComment = true;
n++;
}
break;
case '*':
// If we're not inside a comment, we don't care about finding "*/".
if (!inComment) break;
// Look for the end of a C style comment (i.e. "*/"). If we found one,
// we found a full comment, which we don't allow (VSWhidbey 228396).
if (s[n+1] == '/') return true;
break;
case 'o':
case 'O':
if (IsDangerousOnString(s, n))
return true;
break;
case 's':
case 'S':
if (IsDangerousScriptString(s, n))
return true;
break;
case 'e':
case 'E':
if (IsDangerousExpressionString(s, n))
return true;
break;
#endif // OBSOLETE
}
// Continue searching
i=n+1;
}
}
}
}