Пример #1
0
        public void ImgTagShouldSanitizeCorrectly()
        {
            var str       = "<img src=\"http://joinrpg.ru/a.png\" />";
            var sanitizer = new HtmlSanitizer();

            sanitizer.WhiteListMode = true;
            sanitizer.Tag("img").AllowAttributes("src");
            sanitizer.Sanitize(str).ShouldBe("<img src=\"http://joinrpg.ru/a.png\">");
        }
Пример #2
0
 private static FeedComment ToFeedComment(Comment comment)
 {
     return(new FeedComment(comment.UserID)
     {
         Id = comment.ID.ToString(),
         Description = HtmlSanitizer.Sanitize(comment.Content),
         Date = comment.Datetime
     });
 }
Пример #3
0
        public static string SanitizeHtml(this string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(text);
            }

            return(HtmlSanitizer.Sanitize(text));
        }
Пример #4
0
 private static FeedComment ToFeedComment(ProjectComment comment)
 {
     return(new FeedComment(comment.Comment.CreateBy)
     {
         Id = comment.Comment.ID.ToString(),
         Description = HtmlSanitizer.Sanitize(comment.Comment.Content),
         Date = comment.Comment.CreateOn
     });
 }
Пример #5
0
        public RedirectToRouteResult modifyProc(Credit credit)
        {
            var sanitizer = new HtmlSanitizer();

            credit.contents = sanitizer.Sanitize(credit.contents);
            credit.uptId    = System.Web.HttpContext.Current.User.Identity.Name;
            creditService.updateCredit(credit);
            return(RedirectToAction("list"));
        }
Пример #6
0
 private static FeedComment ToFeedComment(EventComment comment)
 {
     return(new FeedComment(new Guid(comment.Creator))
     {
         Id = comment.Id.ToString(CultureInfo.InvariantCulture),
         Description = HtmlSanitizer.Sanitize(comment.Comment),
         Date = comment.Date
     });
 }
Пример #7
0
        // GET: blogs/search
        public async Task <IActionResult> search(string term)
        {
            if (term == null)
            {
                return(Redirect("/blogs"));
            }

            var _sanitize = new HtmlSanitizer();

            term = _sanitize.Sanitize(UtilityBLL.ReplaceHyphinWithSpace(term));

            /* ***************************************/
            // Process Page Meta & BreaCrumb
            /* ***************************************/
            var _meta = PageMeta.returnPageMeta(new PageQuery()
            {
                controller = ControllerContext.ActionDescriptor.ControllerName,
                index      = ControllerContext.ActionDescriptor.ActionName,
                pagenumber = 1,
                matchterm  = term
            });

            if (Jugnoon.Settings.Configs.GeneralSettings.store_searches)
            {
                //*********************************************
                // User Search Tracking Script
                //********************************************
                if (!TagsBLL.Validate_Tags(term.Trim()) && !term.Trim().Contains("@"))
                {
                    // check if tag doesn't exist
                    var count_tags = await TagsBLL.Count(_context, new TagEntity()
                    {
                        type      = TagsBLL.Types.General,
                        tag_type  = TagsBLL.TagType.UserSearches,
                        isenabled = EnabledTypes.Enabled
                    });

                    if (count_tags == 0)
                    {
                        TagsBLL.Add(_context, term.Trim(), TagsBLL.Types.General, 0, TagsBLL.TagType.UserSearches, EnabledTypes.Enabled, term.Trim());
                    }
                }
            }

            /* List Initialization */
            var ListEntity = new BlogListViewModel()
            {
                QueryOptions = new BlogEntity()
                {
                    term = term,
                },
                BreadItems = _meta.BreadItems
            };


            return(View(ListEntity));
        }
Пример #8
0
        public async Task Handle(ChatNotification notification, CancellationToken cancellationToken)
        {
            if (
                notification.ChatMessage.Message.Trim().StartsWith("!") ||
                _config.IgnoredUsers.Any(iu => iu.Equals(notification.ChatMessage.Username, StringComparison.InvariantCultureIgnoreCase))
                )
            {
                return;
            }

            var sanitizedHtml = System.Net.WebUtility.HtmlDecode(_sanitizer.Sanitize(notification.ChatMessage.Message));
            var emotes        = _mapper.Map <IEnumerable <EmoteDto> >(notification.ChatMessage.EmoteSet.Emotes);

            var userTypes = UserTypes.None;

            if (notification.ChatMessage.IsBroadcaster)
            {
                userTypes |= UserTypes.Broadcaster;
            }
            if (notification.ChatMessage.IsModerator)
            {
                userTypes |= UserTypes.Moderator;
            }
            if (notification.ChatMessage.IsSubscriber)
            {
                userTypes |= UserTypes.Subscriber;
            }
            if (notification.ChatMessage.IsVip)
            {
                userTypes |= UserTypes.Vip;
            }
            if (_config.TeamMembers.Any(tm =>
                                        tm.Id.Equals(notification.ChatMessage.UserId, StringComparison.InvariantCultureIgnoreCase)))
            {
                userTypes |= UserTypes.TeamMember;
            }

            var data = new ChatMessageData
            {
                MessageId           = notification.ChatMessage.Id,
                UserId              = notification.ChatMessage.UserId,
                UserName            = notification.ChatMessage.Username,
                DisplayName         = notification.ChatMessage.DisplayName,
                Message             = sanitizedHtml,
                TeamName            = _config.TeamName,
                TeamShoutoutEnabled = _config.TeamShoutoutEnabled,
                EmoteDetails        = emotes.ToArray(),
                UserTypes           = userTypes
            };

            var bcn = new BasicChatNotification(data);
            await Task.Run(() => _notifierMediatorService.Notify(bcn), cancellationToken);

            // _notifierMediatorService.Notify(bcn);
            // await _twitchHub.Clients.All.SendAsync("ReceiveChatMessage", data, uo, cancellationToken: cancellationToken);
        }
Пример #9
0
        public void Add(Comment comment)
        {
            var sanitizer = new HtmlSanitizer();

            if (comment.Text != null)
            {
                comment.Text = sanitizer.Sanitize(comment.Text.Replace("\n", "<br />"));
            }

            if (comment.Author != null)
            {
                comment.Author = sanitizer.Sanitize(comment.Author.Replace("\n", "<br />"));
            }

            this.cacheService.Remove("AllCommentsCache" + comment.PostId);
            this.cacheService.Remove("AllCommentsCacheCount" + comment.PostId);
            this.comments.Add(comment);
            this.comments.SaveChanges();
        }
Пример #10
0
        public static string WhitewashMarkup(string markup)
        {
            if (!string.IsNullOrWhiteSpace(markup))
            {
                var sanitizer = new HtmlSanitizer(allowedTags: new string[] { string.Empty });
                markup = sanitizer.Sanitize(markup);
            }

            return(markup);
        }
Пример #11
0
        public static string SanitizeReduceMarkup(string markup)
        {
            if (!string.IsNullOrWhiteSpace(markup))
            {
                var sanitizer = new HtmlSanitizer(allowedTags: new string[] { "b", "i", "u", "em", "strong", "q" });
                markup = sanitizer.Sanitize(markup);
            }

            return(markup);
        }
Пример #12
0
        static public String getRutaXSS3()
        {
            string ruta        = "<a href=\"/Articulos/Index/\"onmouseover=\"alert(1234567890)\">INICIO/onmouseover=alert(1234567890)</a>";
            var    sanitizer   = new HtmlSanitizer();
            string rutaSaneada = sanitizer.Sanitize(ruta);

            return(rutaSaneada);

            //    return new HtmlSanitizer().Sanitize("<a href=\"/Articulos/Index/\"onmouseover=\"alert(1234567890)\">INICIO/onmouseover=alert(1234567890)</a>");
        }
Пример #13
0
        public RedirectToRouteResult modifyProc(Business business)
        {
            HttpFileCollectionBase multipartRequest = Request.Files;
            var sanitizer = new HtmlSanitizer();

            business.contents = sanitizer.Sanitize(business.contents);
            business.uptId    = System.Web.HttpContext.Current.User.Identity.Name;
            businessService.updateBusiness(multipartRequest, business);
            return(RedirectToAction("list"));
        }
Пример #14
0
        public RedirectToRouteResult modifyProc(General general)
        {
            HttpFileCollectionBase multipartRequest = Request.Files;
            var sanitizer = new HtmlSanitizer();

            general.contents = sanitizer.Sanitize(general.contents);
            general.uptId    = System.Web.HttpContext.Current.User.Identity.Name;
            generalService.updateGeneral(multipartRequest, general);
            return(RedirectToAction("list"));
        }
Пример #15
0
        public static string SanitizeText(this string text)
        {
            var htmlSanitizer = new HtmlSanitizer();

            htmlSanitizer.KeepChildNodes = true;

            htmlSanitizer.AllowDataAttributes = true;

            return(htmlSanitizer.Sanitize(text));
        }
Пример #16
0
        public async Task <IActionResult> Post([FromBody] BlogPostRequest blogPostRequest)
        {
            var authorId = new Guid(HttpContext.User.FindFirst("authorId").Value);

            blogPostRequest.Title = _sanitizer.Sanitize(blogPostRequest.Title); // Post value: <div onload=alert('xss')>Title</div>
            blogPostRequest.Text  = _sanitizer.Sanitize(blogPostRequest.Text);  // Post value: <script type="text/javascript">alert('text')</script>
            var blogPost = blogPostRequest.CreateBlogPost(authorId);
            await _ctx.BlogPosts.AddAsync(blogPost);

            await _ctx.SaveChangesAsync();

            var blogPostResponse = BlogPostResponse.FromBlogPost(
                _blogPostProtector.Protect(blogPost.Id.ToString()),
                blogPost,
                true
                );

            return(CreatedAtAction(nameof(Get), new { id = _blogPostProtector.Protect(blogPost.Id.ToString()) }, blogPostResponse));
        }
        public static string SanitizeHtmlData(string htmlData)
        {
            var sanitizer = new HtmlSanitizer();

            sanitizer.AllowedTags.Remove("iframe");
            sanitizer.AllowedTags.Remove("img");
            var sanitized = sanitizer.Sanitize(htmlData);

            return(sanitized);
        }
Пример #18
0
        public RedirectToRouteResult registerProc(Product product)
        {
            var sanitizer = new HtmlSanitizer();

            product.contents = sanitizer.Sanitize(product.contents);
            product.regId    = System.Web.HttpContext.Current.User.Identity.Name;
            productService.insertProduct(product);

            return(RedirectToAction("list"));
        }
Пример #19
0
        public async Task <IActionResult> CreateAsync([FromBody] Post body)
        {
            var sanitizer = new HtmlSanitizer();

            body.Content = sanitizer.Sanitize(body.Content);
            _db.Posts.Add(body);
            await _db.SaveChangesAsync();

            return(new OkObjectResult(body));
        }
Пример #20
0
        public IBlogPostData ConvertMarkdownToHtml(IBlogPostData data)
        {
            var title         = data.Title;
            var content       = data.Content;
            var contentAsHtml = MarkdigConverter.ConvertToHtml(content);
            var sanitizedHtml = _sanitizer.Sanitize(contentAsHtml);
            var result        = new BlogPostData(title, sanitizedHtml);

            return(result);
        }
Пример #21
0
        public async Task Replace(string id, ArticleChange model)
        {
            var article = await articleRepository.GetById(id);

            if (article is null)
            {
                throw new ArgumentException($"Article with id {id} not found.");
            }

            if (article.Title != model.Title)
            {
                article.Slug = new SlugHelper().GenerateSlug(model.Title);
            }


            var sanitizer = new HtmlSanitizer();

            model.Body.Blocks = model.Body.Blocks.Select(block =>
            {
                if (block.Data.Text != null)
                {
                    block.Data.Text = sanitizer.Sanitize(block.Data.Text);
                }
                if (block.Data.Caption != null)
                {
                    block.Data.Caption = sanitizer.Sanitize(block.Data.Caption);
                }

                return(block);
            }).ToList();

            article.Title  = model.Title;
            article.Lead   = model.Lead;
            article.Body   = model.Body;
            article.Cover  = model.Cover;
            article.Author = model.Author;
            article.Tags   = model.Tags;
            if (model.Schedule != DateTime.MinValue)
            {
                article.Schedule = model.Schedule;
            }
            await articleRepository.Replace(article);
        }
Пример #22
0
        public void Add(Post post)
        {
            var sanitizer = new HtmlSanitizer();

            if (post.Text != null)
            {
                post.Text = sanitizer.Sanitize(post.Text.Replace("\n", "<br />"));
            }

            if (post.Author != null)
            {
                post.Author = sanitizer.Sanitize(post.Author.Replace("\n", "<br />"));
            }

            this.cacheService.Remove("AllPostsCache" + post.ForumId);
            this.cacheService.Remove("AllPostsCacheCount" + post.ForumId);
            this.posts.Add(post);
            this.posts.SaveChanges();
        }
Пример #23
0
        protected void SetHtml(string txt, string html)

        {
            if (string.IsNullOrEmpty(html))
            {
                return;
            }

            _dictionary[txt] = HtmlSanitizer.Sanitize(html);
        }
Пример #24
0
        public async Task <IActionResult> Create(AdminControllerCreateViewModel viewModel)
        {
            if (ModelState.IsValid == false)
            {
                viewModel.Departments = await LoadDepartmentSelectList();

                return(View(viewModel));
            }

            // insert application

            var vacancyModel = new VacancyBaseModel
            {
                JobTitle       = _htmlSanitizer.Sanitize(viewModel.Vacancy.JobTitle),
                JobDescription = _htmlSanitizer.Sanitize(viewModel.Vacancy.JobDescription),
                SalaryMin      = (int)viewModel.Vacancy.SalaryMin,
                SalaryMax      = (int)viewModel.Vacancy.SalaryMax,
                DepartmentId   = (int)viewModel.Department,
                ContractType   = _htmlSanitizer.Sanitize(viewModel.Vacancy.ContractType),
                StartDate      = viewModel.Vacancy.StartDate,
                EndDate        = viewModel.Vacancy.EndDate,
                Published      = viewModel.Vacancy.Published
            };

            var questionModels = new List <VacancyQuestionBaseModel>();

            foreach (var question in viewModel.Questions)
            {
                questionModels.Add(new VacancyQuestionBaseModel
                {
                    Question     = _htmlSanitizer.Sanitize(question.Question),
                    IsRequired   = question.IsRequired,
                    MinLength    = question.MinLength,
                    MaxLength    = question.MaxLength,
                    DisplayOrder = question.DisplayOrder
                });
            }

            var vacancyId = await _vacancyCrud.Insert(vacancyModel, questionModels);

            return(Redirect($"/admin/details/{vacancyId}"));
        }
        public IActionResult ShowPage(int PageID, string returnUrl)
        {
            var docpage   = Documentation.Pages.FirstOrDefault(x => x.DocPageID == PageID);
            var sanitizer = new HtmlSanitizer();

            sanitizer.AllowedAttributes.Add("class");
            if (docpage.GroupID == 0)
            {
                var model = new ShowPublicPageViewModel
                {
                    Name         = docpage.Name,
                    returnUrl    = returnUrl,
                    Files        = Files.DocumentationFiles.Where(x => x.DocPageId == PageID).ToList(),
                    DocPageID    = PageID,
                    HtmlDataText = sanitizer.Sanitize(CommonMark.CommonMarkConverter.Convert(docpage.Data ?? @"### No content ")),
                    Date         = docpage.Date.ToShortDateString()
                };
                return(View("ShowPublicDocPage", model));
            }
            else
            {
                var List = new List <TaskModel>();
                foreach (var item in Documentation.Tasks.Where(x => x.DocPageID == PageID).ToList())
                {
                    List.Add(new TaskModel()
                    {
                        Task = item, User = Users.UsersData.FirstOrDefault(x => x.Id == item.UserID)
                    });
                }
                var model = new ShowPrivatePageViewModel {
                    Name         = docpage.Name,
                    returnUrl    = returnUrl,
                    Files        = Files.DocumentationFiles.Where(x => x.DocPageId == PageID).ToList(),
                    DocPageID    = PageID,
                    HtmlDataText = sanitizer.Sanitize(CommonMark.CommonMarkConverter.Convert(docpage.Data ?? @"### No content ")),
                    Date         = docpage.Date.ToShortDateString(),
                    GroupID      = docpage.GroupID,
                    Tasks        = List
                };
                return(View("ShowPrivateDocPage", model));
            }
        }
Пример #26
0
        /// <summary>
        /// Returns a string with any html removed
        /// </summary>
        /// <param name="s">The string to check</param>
        /// <returns>The sanitized string</returns>
        public static string StripHtml(this string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return(s);
            }

            var htmlSanitizer = new HtmlSanitizer();

            return(htmlSanitizer.Sanitize(s));
        }
Пример #27
0
        static void Clean(string name, string pathDirty, string pathClean)
        {
            string html = File.ReadAllText(pathDirty + name);

            HtmlSanitizer sanitizer = new HtmlSanitizer();

            sanitizer.AllowedTags.Remove("img");
            string cleanHtml = sanitizer.Sanitize(html);

            File.WriteAllText(pathClean + name, cleanHtml);
        }
Пример #28
0
        public RedirectToRouteResult modifyProc(News news)
        {
            HttpFileCollectionBase multipartRequest = Request.Files;

            news.uptId = System.Web.HttpContext.Current.User.Identity.Name;
            var sanitizer = new HtmlSanitizer();

            news.contents = sanitizer.Sanitize(news.contents);
            newsService.updateNews(multipartRequest, news);
            return(RedirectToAction("list", (RouteValueDictionary)Session["searchMap"]));
        }
Пример #29
0
        public string RemoveHtmlXss(string html)
        {
            if (string.IsNullOrEmpty(html))
            {
                return("");
            }

            var _htmlSanitizer = new HtmlSanitizer();

            return(_htmlSanitizer.Sanitize(html, null));
        }
        public string Run(String jobId)
        {
            Logger.DebugFormat("Sanitize HTML for {0}", jobId);
            string html      = File.ReadAllText(_filePath);
            var    sanitizer = new HtmlSanitizer();
            var    sanitized = sanitizer.Sanitize(html);

            File.WriteAllText(_filePath, sanitized);
            Logger.DebugFormat("Sanitize HTML for {0} done!", jobId);
            return(_filePath);
        }
Пример #31
0
        public void XSSLocatorTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();

            // Act
            string htmlFragment = "<a href=\"'';!--\"<XSS>=&{()}\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = @"<a href=""'';!--"">=&amp;{()}&quot;&gt;</a>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #32
0
        public void ImageXSS2Test()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG SRC=javascript:alert('XSS')>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<IMG>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #33
0
        public void DivBackgroundImageWithUnicodedXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = @"<DIV STYLE=""background-image:\0075\0072\006C\0028'\006a\0061\0076\0061\0073\0063\0072\0069\0070\0074\003a\0061\006c\0065\0072\0074\0028\0027\0058\0053\0053\0027\0029'\0029"">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<div></div>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #34
0
        public void ImageMultilineInjectedXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = @"<IMG
SRC
=
""
j
a
v
a
s
c
r
i
p
t
:
a
l
e
r
t
(
'
X
S
S
'
)
""
>
";

            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<img>\n";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #35
0
        public void TDXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<TABLE><TD BACKGROUND=\"javascript:alert('XSS')\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<table><tbody><tr><td></td></tr></tbody></table>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #36
0
        public void EmbedSVGXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<EMBED SRC=\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\" type=\"image/svg+xml\" AllowScriptAccess=\"always\"></EMBED>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #37
0
        public void XmlWithCDataXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<XML ID=I><X><C><![CDATA[<IMG SRC=\"javas]]><![CDATA[cript:alert('XSS');\">]]></C></X></xml><SPAN DATASRC=#I DATAFLD=C DATAFORMATAS=HTML></SPAN>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<SPAN></SPAN>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #38
0
        public void ImageStyleExpressionXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG STYLE=\"xss:expr/*XSS*/ession(alert('XSS'))\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<IMG>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #39
0
        public void BaseTagXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<BASE HREF=\"javascript:alert('XSS');//\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #40
0
        public void ImageInputXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<INPUT TYPE=\"IMAGE\" SRC=\"javascript:alert('XSS');\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<input type=\"image\">";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #41
0
        public void BRJavascriptIncludeXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<BR SIZE=\"&{alert('XSS')}\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<BR>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #42
0
        public void ImageDoubleOpenAngleBracketXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<image src=http://ha.ckers.org/scriptlet.html <";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #43
0
        public void DivJavascriptEscapingXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<div style=\"\";alert('XSS');//\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<div></div>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #44
0
        public void ImageSpaceAndMetaCharXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG SRC=\" &#14;  javascript:alert('XSS');\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<img>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #45
0
        public void ImageNullBreaksUpXSSTest2()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<SCR\0IPT>alert(\"XSS\")</SCR\0IPT>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #46
0
        public void ImageNullBreaksUpXSSTest1()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG SRC=java\0script:alert(\"XSS\")>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<img>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #47
0
        public void DivBackgroundImageWithExtraCharactersXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<DIV STYLE=\"background-image: url(&#1;javascript:alert('XSS'))\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<div></div>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #48
0
        public void PWithUrlInStyleXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<p STYLE=\"behavior: url(www.ha.ckers.org);\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            // intentionally keep it failing to get notice when reviewing unit tests so can disucss
            string expected = "<p></p>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #49
0
        public void DivExpressionXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<DIV STYLE=\"width: expression(alert('XSS'));\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<div></div>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #50
0
        public void ImageWithVBScriptXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG SRC='vbscript:msgbox(\"XSS\")'>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<img>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #51
0
        public void AnchorTagStyleExpressionXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "exp/*<A STYLE='no\\xss:noxss(\"*//*\");xss:&#101;x&#x2F;*XSS*//*/*/pression(alert(\"XSS\"))'>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "exp/*<a></a>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #52
0
 public void PostProcessTest()
 {
     var sanitizer = new HtmlSanitizer();
     sanitizer.PostProcessNode += (s, e) =>
     {
         if (e.Node is IDomElement)
         {
             e.Node.AddClass("test");
             e.Node.AppendChild(CsQuery.CQ.Create("<b>Test</b>").FirstElement());
         }
     };
     var html = @"<div>Hallo</div>";
     var sanitized = sanitizer.Sanitize(html);
     Assert.That(sanitized, Is.EqualTo(@"<div class=""test"">Hallo<b>Test</b></div>").IgnoreCase);
 }
Пример #53
0
        public void EmbedTagXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<EMBED SRC=\"http://ha.ckers.org/xss.swf\" AllowScriptAccess=\"always\"></EMBED>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #54
0
 public void AutoLinkTest()
 {
     var sanitizer = new HtmlSanitizer();
     var autolink = new AutoLink();
     sanitizer.PostProcessNode += (s, e) =>
     {
         var text = e.Node as IDomText;
         if (text != null)
         {
             var autolinked = autolink.Link(text.NodeValue);
             if (autolinked != text.NodeValue)
                 foreach (var node in CQ.Create(autolinked))
                     e.ReplacementNodes.Add(node);
         }
     };
     var html = @"<div>Click here: http://example.com/.</div>";
     Assert.That(sanitizer.Sanitize(html), Is.EqualTo(@"<div>Click here: <a href=""http://example.com/"">http://example.com/</a>.</div>").IgnoreCase);
     Assert.That(sanitizer.Sanitize("Check out www.google.com."), Is.EqualTo(@"Check out <a href=""http://www.google.com"">www.google.com</a>.").IgnoreCase);
 }
Пример #55
0
        public void XmlNamespaceXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<HTML xmlns:xss>  <?import namespace=\"xss\" implementation=\"http://ha.ckers.org/xss.htc\">  <xss:xss>XSS</xss:xss></HTML>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #56
0
        public void FrameXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<FRAMESET><FRAME SRC=\"javascript:alert('XSS');\"></FRAMESET>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #57
0
        public void ImageWithLivescriptXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG SRC=\"Livescript:[code]\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<img>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #58
0
        public void ImageEmbeddedCarriageReturnXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG SRC=\"jav&#x0D;ascript:alert('XSS');\">";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<img>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #59
0
        public void ImageHexEncodeXSSTest()
        {
            // Arrange
            var sanitizer = new HtmlSanitizer();


            // Act
            string htmlFragment = "<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>";
            string actual = sanitizer.Sanitize(htmlFragment);

            // Assert
            string expected = "<img>";
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }
Пример #60
0
        public void RussianTextTest()
        {
            // Arrange
            var s = new HtmlSanitizer();

            // Act
            var htmlFragment = "Тест";
            var outputFormatter = new CsQuery.Output.FormatDefault(DomRenderingOptions.RemoveComments | DomRenderingOptions.QuoteAllAttributes, HtmlEncoders.Minimum);
            var actual = s.Sanitize(htmlFragment, "", outputFormatter);

            // Assert
            var expected = htmlFragment;
            Assert.That(actual, Is.EqualTo(expected).IgnoreCase);
        }