private string RenderSnippet(IHttpContext httpContext) { if (!telemetryConfiguration.DisableTelemetry && !string.IsNullOrEmpty(telemetryConfiguration.InstrumentationKey)) { string additionalJS = string.Empty; IIdentity identity = httpContext.User?.Identity; if (EnableAuthSnippet && identity != null && identity.IsAuthenticated) { string escapedUserName = encoder.Encode(identity.Name); additionalJS = string.Format(CultureInfo.InvariantCulture, AuthSnippet, escapedUserName); } return(string.Format(CultureInfo.InvariantCulture, Snippet, telemetryConfiguration.InstrumentationKey, additionalJS)); } else { return(string.Empty); } }
private void AppendEncodedVersionedSrc( string srcName, string srcValue, TagHelperContent builder, bool generateForDocumentWrite) { if (AppendVersion == true) { srcValue = _fileVersionProvider.AddFileVersionToPath(srcValue); } if (generateForDocumentWrite) { // srcValue comes from a C# context and globbing. Must HTML-encode it to ensure the // written <script/> element is valid. Must also JavaScript-encode that value to ensure // the document.write() statement is valid. srcValue = HtmlEncoder.Encode(srcValue); srcValue = JavaScriptEncoder.Encode(srcValue); } AppendAttribute(builder, srcName, srcValue, escapeQuotes: generateForDocumentWrite); }
private void AppendFallbackHrefs(TagHelperContent builder, IReadOnlyList <string> fallbackHrefs) { builder.AppendHtml("["); var firstAdded = false; // Perf: Avoid allocating enumerator and read interface .Count once rather than per iteration var fallbackHrefsCount = fallbackHrefs.Count; for (var i = 0; i < fallbackHrefsCount; i++) { if (firstAdded) { builder.AppendHtml(",\""); } else { builder.AppendHtml("\""); firstAdded = true; } // fallbackHrefs come from bound attributes (a C# context) and globbing. Must always be non-null. Debug.Assert(fallbackHrefs[i] != null); var valueToWrite = fallbackHrefs[i]; if (AppendVersion == true) { valueToWrite = FileVersionProvider.AddFileVersionToPath(ViewContext.HttpContext.Request.PathBase, fallbackHrefs[i]); } // Must HTML-encode the href attribute value to ensure the written <link/> element is valid. Must also // JavaScript-encode that value to ensure the doc.write() statement is valid. valueToWrite = HtmlEncoder.Encode(valueToWrite); valueToWrite = JavaScriptEncoder.Encode(valueToWrite); builder.AppendHtml(valueToWrite); builder.AppendHtml("\""); } builder.AppendHtml("]"); }
public async Task <IActionResult> Register(UserToRegisterDTO userToRegister) { try { userToRegister.Email = _htmlEncoder.Encode(_javaScriptEncoder.Encode(userToRegister.Email)); userToRegister.Username = _htmlEncoder.Encode(_javaScriptEncoder.Encode(userToRegister.Username)); if (await _userService.UserExists(userToRegister.Username)) { return(StatusCode(400, "Username already taken")); } if (!_userService.IsValidEmail(userToRegister.Email)) { return(StatusCode(400, "Invalid email")); } var user = await _userService.Register(userToRegister); return(StatusCode(200, user)); } catch { return(StatusCode(500, "Something went wrong while attempting to register, please try again in a few moments.")); } }
public void JavaScriptEncode_AboveAscii_Relaxed() { // Arrange JavaScriptEncoder encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; // Act & assert for (int i = 0x128; i <= 0xFFFF; i++) { if (IsSurrogateCodePoint(i)) { continue; // surrogates don't matter here } UnicodeCategory category = char.GetUnicodeCategory((char)i); if (category != UnicodeCategory.NonSpacingMark) { continue; // skip undefined characters like U+0378, or spacing characters like U+2028 } string javaScriptEncoded = encoder.Encode(char.ConvertFromUtf32(i)); Assert.True(char.ConvertFromUtf32(i) == javaScriptEncoded, i.ToString()); } }
public async Task <ActionResult <IList <PersonResponse> > > PostPersonBySearchTerm([FromBody] string term) { try { term = _encoder.Encode(term); var searchTerm = new SearchTermRequest(term); var personsResponse = await _bookingsApiClient.PostPersonBySearchTermAsync(searchTerm); personsResponse = personsResponse?.Where(p => !p.ContactEmail.Contains(_testSettings.TestUsernameStem)).ToList(); return(Ok(personsResponse)); } catch (BookingsApiException e) { if (e.StatusCode == (int)HttpStatusCode.BadRequest) { return(BadRequest(e.Response)); } throw; } }
private void BuildFallbackBlock(TagHelperContent builder) { EnsureGlobbingUrlBuilder(); var fallbackHrefs = GlobbingUrlBuilder.BuildUrlList( FallbackHref, FallbackHrefInclude, FallbackHrefExclude); if (fallbackHrefs.Count == 0) { return; } builder.AppendHtml(HtmlString.NewLine); // Build the <meta /> tag that's used to test for the presence of the stylesheet builder .AppendHtml("<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"") .Append(FallbackTestClass) .AppendHtml("\" />"); // Build the <script /> tag that checks the effective style of <meta /> tag above and renders the extra // <link /> tag to load the fallback stylesheet if the test CSS property value is found to be false, // indicating that the primary stylesheet failed to load. // GetEmbeddedJavaScript returns JavaScript to which we add '"{0}","{1}",{2});' builder .AppendHtml("<script>") .AppendHtml(JavaScriptResources.GetEmbeddedJavaScript(FallbackJavaScriptResourceName)) .AppendHtml("\"") .AppendHtml(JavaScriptEncoder.Encode(FallbackTestProperty)) .AppendHtml("\",\"") .AppendHtml(JavaScriptEncoder.Encode(FallbackTestValue)) .AppendHtml("\","); AppendFallbackHrefs(builder, fallbackHrefs); builder.AppendHtml("</script>"); }
public async Task <ActionResult> GetBookingsList(string cursor, int limit = 100) { if (cursor != null) { cursor = _encoder.Encode(cursor); } IEnumerable <string> caseTypes; if (_userIdentity.IsAdministratorRole()) { caseTypes = _userIdentity.GetGroupDisplayNames(); } else { return(Unauthorized()); } try { var types = caseTypes ?? Enumerable.Empty <string>(); var hearingTypesIds = await GetHearingTypesId(types); var bookingsResponse = await _bookingsApiClient.GetHearingsByTypesAsync(hearingTypesIds, cursor, limit); return(Ok(bookingsResponse)); } catch (BookingsApiException e) { if (e.StatusCode == (int)HttpStatusCode.BadRequest) { return(BadRequest(e.Response)); } throw; } }
public ActionResult Process ( [ModelBinder(typeof(JTokenModelBinder))] JToken parameters ) { var script = parameters["callback"].Value <string>(); //Anti-XSS var callback = HttpUtility.JavaScriptStringEncode(script); Console.WriteLine(callback); callback = _javaScriptEncoder.Encode(script); Console.WriteLine(callback); var content = $"{callback}({parameters.ToString()})"; return (Content ( content , "text/javascript" )); }
private void BuildFallbackBlock(TagHelperAttributeList attributes, TagHelperContent builder) { EnsureGlobbingUrlBuilder(); var fallbackSrcs = GlobbingUrlBuilder.BuildUrlList(FallbackSrc, FallbackSrcInclude, FallbackSrcExclude); if (fallbackSrcs.Count > 0) { // Build the <script> tag that checks the test method and if it fails, renders the extra script. builder.AppendHtml(Environment.NewLine) .AppendHtml("<script>(") .AppendHtml(FallbackTestExpression) .AppendHtml("||document.write(\""); foreach (var src in fallbackSrcs) { // Fallback "src" values come from bound attributes and globbing. Must always be non-null. Debug.Assert(src != null); StringWriter.Write("<script"); var addSrc = true; // Perf: Avoid allocating enumerator for (var i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; if (!attribute.Name.Equals(SrcAttributeName, StringComparison.OrdinalIgnoreCase)) { if (SuppressFallbackIntegrity && string.Equals(IntegrityAttributeName, attribute.Name, StringComparison.OrdinalIgnoreCase)) { continue; } StringWriter.Write(' '); attribute.WriteTo(StringWriter, HtmlEncoder); } else { addSrc = false; WriteVersionedSrc(attribute.Name, src, attribute.ValueStyle, StringWriter); } } if (addSrc) { WriteVersionedSrc(SrcAttributeName, src, HtmlAttributeValueStyle.DoubleQuotes, StringWriter); } StringWriter.Write("></script>"); } var stringBuilder = StringWriter.GetStringBuilder(); var scriptTags = stringBuilder.ToString(); stringBuilder.Clear(); var encodedScriptTags = JavaScriptEncoder.Encode(scriptTags); builder.AppendHtml(encodedScriptTags); builder.AppendHtml("\"));</script>"); } }
private static string JavaScriptEncode(string content) { return(_javaScriptEncoder.Encode(content)); }
private void BuildFallbackBlock(TagHelperAttributeList attributes, TagHelperContent builder) { EnsureGlobbingUrlBuilder(); var fallbackHrefs = GlobbingUrlBuilder.BuildUrlList( FallbackHref, FallbackHrefInclude, FallbackHrefExclude); if (fallbackHrefs.Count == 0) { return; } builder.AppendHtml(HtmlString.NewLine); // Build the <meta /> tag that's used to test for the presence of the stylesheet builder .AppendHtml("<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"") .Append(FallbackTestClass) .AppendHtml("\" />"); // Build the <script /> tag that checks the effective style of <meta /> tag above and renders the extra // <link /> tag to load the fallback stylesheet if the test CSS property value is found to be false, // indicating that the primary stylesheet failed to load. // GetEmbeddedJavaScript returns JavaScript to which we add '"{0}","{1}",{2});' builder .AppendHtml("<script>") .AppendHtml(JavaScriptResources.GetEmbeddedJavaScript(FallbackJavaScriptResourceName)) .AppendHtml("\"") .AppendHtml(JavaScriptEncoder.Encode(FallbackTestProperty)) .AppendHtml("\",\"") .AppendHtml(JavaScriptEncoder.Encode(FallbackTestValue)) .AppendHtml("\","); AppendFallbackHrefs(builder, fallbackHrefs); builder.AppendHtml(", \""); // Perf: Avoid allocating enumerator for (var i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; if (string.Equals(attribute.Name, HrefAttributeName, StringComparison.OrdinalIgnoreCase)) { continue; } if (SuppressFallbackIntegrity && string.Equals(attribute.Name, IntegrityAttributeName, StringComparison.OrdinalIgnoreCase)) { continue; } attribute.WriteTo(StringWriter, HtmlEncoder); StringWriter.Write(' '); } var stringBuilder = StringWriter.GetStringBuilder(); var scriptTags = stringBuilder.ToString(); stringBuilder.Clear(); var encodedScriptTags = JavaScriptEncoder.Encode(scriptTags); builder.AppendHtml(encodedScriptTags); builder.AppendHtml("\");</script>"); }
public string JavaScriptEncode(string content) { return(JavaScriptEncoder.Encode(content)); }
/// <summary> /// 异步访问并呈现当前标签实例。 /// </summary> /// <param name="context">当前HTML标签上下文,包含当前HTML相关信息。</param> /// <param name="output">当前标签输出实例,用于呈现标签相关信息。</param> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = null; AppendLibraries(output); var content = await output.GetChildContentAsync(); if (!content.IsEmptyOrWhiteSpace) { output.AppendHtml(content.GetContent().Trim()); } if (AttachStatusMessage) { var status = GetStatusMessage(); if (status != null) { output.AppendHtml("script", x => { x.MergeAttribute("type", "text/javascript"); x.InnerHtml.AppendHtml("$(function(){"); x.InnerHtml.AppendHtml($"if(window.showMsg){{showMsg({status.ToJsonString()});}}else{{alert('{_scriptEncoder.Encode(status.Message)}');}}"); x.InnerHtml.AppendHtml("});"); }); } } if (GenerateAntiforgery) { output.AppendHtml("form", builder => { builder.GenerateId("ajax-protected-form", "-"); builder.MergeAttribute("method", "post"); builder.MergeAttribute("action", HttpContext.Request.Path); builder.InnerHtml.AppendHtml(_generator.GenerateAntiforgery(ViewContext)); }); } }
public List <Payee> Get(string name) { var filter = "{$where: \"function() {return this.Name == '" + _jsEncoder.Encode(name) + "'}\"}"; return(payees.Find(filter).ToList()); }
private void BuildFallbackBlock(TagHelperAttributeList attributes, DefaultTagHelperContent builder) { EnsureGlobbingUrlBuilder(); var fallbackSrcs = GlobbingUrlBuilder.BuildUrlList(FallbackSrc, FallbackSrcInclude, FallbackSrcExclude); if (fallbackSrcs.Count > 0) { // Build the <script> tag that checks the test method and if it fails, renders the extra script. builder.AppendHtml(Environment.NewLine) .AppendHtml("<script>(") .AppendHtml(FallbackTestExpression) .AppendHtml("||document.write(\""); // May have no "src" attribute in the dictionary e.g. if Src and SrcInclude were not bound. if (!attributes.ContainsName(SrcAttributeName)) { // Need this entry to place each fallback source. attributes.Add(new TagHelperAttribute(SrcAttributeName, value: null)); } foreach (var src in fallbackSrcs) { // Fallback "src" values come from bound attributes and globbing. Must always be non-null. Debug.Assert(src != null); builder.AppendHtml("<script"); // Perf: Avoid allocating enumerator for (var i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; if (!attribute.Name.Equals(SrcAttributeName, StringComparison.OrdinalIgnoreCase)) { var encodedKey = JavaScriptEncoder.Encode(attribute.Name); var attributeValue = attribute.Value.ToString(); var encodedValue = JavaScriptEncoder.Encode(attributeValue); AppendAttribute(builder, encodedKey, encodedValue, escapeQuotes: true); } else { // Ignore attribute.Value; use src instead. var attributeValue = src; if (AppendVersion == true) { attributeValue = _fileVersionProvider.AddFileVersionToPath(attributeValue); } // attribute.Key ("src") does not need to be JavaScript-encoded. var encodedValue = JavaScriptEncoder.Encode(attributeValue); AppendAttribute(builder, attribute.Name, encodedValue, escapeQuotes: true); } } builder.AppendHtml("><\\/script>"); } builder.AppendHtml("\"));</script>"); } }
public IActionResult SQLInjection() { string name = RequestUtils.GetIfDefined(Request, "name"); string pw = RequestUtils.GetIfDefined(Request, "pw"); string res = ""; if (name.Length > 0) { var command = new SQLiteCommand($"SELECT * FROM users WHERE name = '{name}' and pw = '{pw}'", DatabaseUtils._con); using (var reader = command.ExecuteReader()) { while (reader.Read()) { res += reader["name"] + ""; } } Show("Successfully logged in as " + _javaScriptEncoder.Encode(res)); } if (res.Length == 0) { Show("Please login by providing a valid username and password"); } return(View()); }
public void JavaScriptEncode_Relaxed_StillEncodesForbiddenChars_Extended() { // Arrange JavaScriptEncoder encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; // Act & assert - BMP chars for (int i = 0; i <= 0xFFFF; i++) { string input = new string((char)i, 1); string expected; if (IsSurrogateCodePoint(i)) { expected = "\\uFFFD"; // unpaired surrogate -> Unicode replacement char } else { if (input == "\b") { expected = @"\b"; } else if (input == "\t") { expected = @"\t"; } else if (input == "\n") { expected = @"\n"; } else if (input == "\f") { expected = @"\f"; } else if (input == "\r") { expected = @"\r"; } else if (input == "\\") { expected = @"\\"; } else if (input == "\"") { expected = "\\\""; } else { bool mustEncode = false; if (i <= 0x001F || (0x007F <= i && i <= 0x9F)) { mustEncode = true; // control char } else if (!UnicodeTestHelpers.IsCharacterDefined((char)i)) { mustEncode = true; // undefined (or otherwise disallowed) char } if (mustEncode) { expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}", i); } else { expected = input; // no encoding } } } string retVal = encoder.Encode(input); Assert.Equal(expected, retVal); } // Act & assert - astral chars for (int i = 0x10000; i <= 0x10FFFF; i++) { string input = char.ConvertFromUtf32(i); string expected = string.Format(CultureInfo.InvariantCulture, @"\u{0:X4}\u{1:X4}", (uint)input[0], (uint)input[1]); string retVal = encoder.Encode(input); Assert.Equal(expected, retVal); } }