private static JoinHtmlString PerformRender(MarkdownString markdownString, ILinkRenderer?linkRenderer, Action <string, TextWriter, MarkdownPipeline, MarkdownParserContext> renderMethod, IHtmlSanitizer sanitizer) { linkRenderer ??= DoNothingLinkRenderer.Instance; if (markdownString?.Contents == null) { return("".MarkAsHtmlString()); } var context = new MarkdownParserContext(); var contents = sanitizer.Sanitize(markdownString.Contents); //TODO - do we need to save re-use pipeline? var pipeline = new MarkdownPipelineBuilder() .UseSoftlineBreakAsHardlineBreak() .UseMediaLinks() .UseAutoLinks() .UseEntityLinker(linkRenderer) .Build(); var writer = new StringWriter(); renderMethod(contents, writer, pipeline, context); var rendered = writer.ToString(); return(sanitizer.Sanitize(rendered).MarkAsHtmlString()); }
public ServiceResult <ArticleEntity> Create(ArticleEntity article) { var validResult = ValidArticleType(article); if (validResult.HasViolation) { return(validResult); } article.ArticleContent = _htmlSanitizer.Sanitize(article.ArticleContent); return(_articleService.Add(article)); }
public async Task <IActionResult> CreateCommentAsync(Guid membershipUserId, string slug, Guid discussionId, Comment comment, CancellationToken cancellationToken) { if (!ModelState.IsValid) { return(BadRequest()); } comment.Content = _htmlSanitizer.Sanitize(comment.Content); var commentId = await _commentService.CreateCommentAsync(membershipUserId, slug, discussionId, comment, cancellationToken); return(Ok(commentId)); }
public async Task <ActionResult> Create( string clubInitials, AnnouncementWithOptions model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; try { var clubId = await _clubService.GetClubId(clubInitials); if (!await _authService.CanUserEdit(User, clubId)) { return(Unauthorized()); } model.ClubId = clubId; if (!ModelState.IsValid) { return(View(model)); } model.Content = _sanitizer.Sanitize(model.Content); model.CreatedBy = await GetUserStringAsync(); model.CreatedDate = DateTime.UtcNow; model.CreatedLocalDate = DateTime.UtcNow.AddMinutes(0 - model.TimeOffset); await _announcementService.SaveNew(model); if (!string.IsNullOrWhiteSpace(returnUrl)) { return(Redirect(returnUrl)); } return(RedirectToAction("Index", "Admin")); } catch { AnnouncementWithOptions vm; if (model.RegattaId.HasValue) { vm = await _announcementService.GetBlankAnnouncementForRegatta( clubInitials, model.RegattaId.Value); } else { vm = model; } return(View(vm)); } }
public async Task <List <SpecialInstructionData> > GetSpecialInstructionsAsync() { var userPrimaryCustomerId = _context.Users.SingleOrDefault(u => u.IdentUserId == _userContext.UserId)?.PrimaryCustomerId; var entities = await _context.SpecialInstructions.AsNoTracking() .Include(x => x.SpecialInstructionEquipment) .ThenInclude(x => x.Equipment) .Where(x => x.CustomerId == userPrimaryCustomerId) .ToListAsync(); var result = _mapper.Map <List <SpecialInstructionData> >(entities); result.ForEach(x => x.Comments = _htmlSanitizer.Sanitize(x.Comments)); return(result); }
public virtual StoryContent Convert(string url, string html) { Check.Argument.IsNotInvalidWebUrl(url, "url"); Check.Argument.IsNotEmpty(html, "html"); Document doc = new Document(); doc.LoadHtml(html); string title = GetTitle(doc); string content = GetContent(doc); if (!string.IsNullOrEmpty(content)) { content = _sanitizer.Sanitize(content); if (!string.IsNullOrEmpty(content)) { content = content.WrapAt(512); } } string trackbackUrl = GetTrackbackUrl(html) ?? GetTrackbackUrl(url, doc); return(new StoryContent(title, content, trackbackUrl)); }
public async Task <IActionResult> CreateDiscussionAsync(Guid userId, string slug, Discussion discussion, CancellationToken cancellationToken) { discussion.Content = _htmlSanitizer.Sanitize(discussion.Content); await _discussionService.CreateDiscussionAsync(userId, slug, discussion, cancellationToken); return(Ok()); }
public void Sanitize_Should_Return_Clean_Html(string target) { const string MalformHtml = "<p><strong>This is a malformed html</strong><label>A label</label> <script>alert('I am running')</script><a href=\"javascript:void:(0)\"></a><div>This is under a div.<a href=\"jscript:alert('foobar')\">A script link</a></div><pre onclick=\"alert('Another alert')\"><code> a line of code</code></pre></p>"; var result = _sanitizer.Sanitize(MalformHtml); Assert.DoesNotContain(target, result); }
public string Sanitize(string markup) { if (markup == null) { return(null); } return(sanitizer.Sanitize(markup)); }
public override PageHtml Invoke(PageHtml pageHtml) { if (_sanitizer != null) { pageHtml.Html = _sanitizer.Sanitize(pageHtml.Html); } return(pageHtml); }
public async Task <string> SanitizeHtml(string rawHtml) { await UpdateSettings(); var sanitizedUserInput = _htmlSanitizer.Sanitize(rawHtml); sanitizedUserInput = sanitizedUserInput.Replace(">", ">"); return(sanitizedUserInput); }
public ServiceResult <ProductEntity> Create(ProductEntity product) { var validResult = ValidProductType(product); if (validResult.HasViolation) { return(validResult); } if (product.ProductImages != null) { foreach (var item in product.ProductImages) { item.ActionType = ActionType.Create; } } product.ProductContent = _htmlSanitizer.Sanitize(product.ProductContent); return(_productService.Add(product)); }
public async Task SendMessage(string content) { MessageCreateInputModel model = new MessageCreateInputModel { Content = htmlSanitizer.Sanitize(content) }; string userId = Context.UserIdentifier; string username = Context.User.Identity.Name; await messageService.Create(model, userId); await Clients.All.SendAsync("ReceiveMessage", username, content); }
public async Task Send(string message) { var sanitizedMessage = _htmlSanitizer.Sanitize(message); await this.Clients.All.SendAsync( "NewMessage", new Message { User = this.Context.User.Identity.Name, Text = sanitizedMessage, }); }
private static IHtmlString PerformRender(MarkdownString markdownString, ILinkRenderer linkRenderer, Func <string, MarkdownPipeline, string> renderMethod, IHtmlSanitizer sanitizer) { linkRenderer = linkRenderer ?? DoNothingLinkRenderer.Instance; if (markdownString?.Contents == null) { return(new HtmlString("")); } var contents = sanitizer.Sanitize(markdownString.Contents); //TODO - do we need to save re-use pipeline? var pipeline = new MarkdownPipelineBuilder() .UseSoftlineBreakAsHardlineBreak() .UseAutoLinks() .UseEntityLinker(linkRenderer) .Build(); return(new HtmlString(sanitizer.Sanitize(renderMethod(contents, pipeline)))); }
public async Task <string> SanitizeAsync(string body, bool escapeExecutable) { var intermediate = escapeExecutable ? _allowAllButNotExecutable.Sanitize(body) : body; var document = new HtmlDocument(); document.LoadHtml(intermediate); var nodes = document.DocumentNode.SelectNodes("//img"); if (nodes != null) { foreach (var node in nodes) { var srcAttr = node.Attributes.Single(a => a.Name == "src"); var src = srcAttr.Value; //src = await TrySanitizeImage(src); if (src == null) { node.Remove(); } else { srcAttr.Value = src; const string ATTRIBUTE = "class"; if (!node.Attributes.Any(a => a.Name == ATTRIBUTE)) { node.Attributes.Add(ATTRIBUTE, ""); } if (string.IsNullOrEmpty(node.Attributes[ATTRIBUTE].Value)) { node.Attributes[ATTRIBUTE].Value = "rounded img-fluid"; } else { node.Attributes[ATTRIBUTE].Value += " rounded img-fluid"; } } } } var ms = new MemoryStream(); var writer = new StreamWriter(ms); document.Save(writer); writer.Flush(); ms.Position = 0; var sanitized = new StreamReader(ms).ReadToEnd(); return(sanitized); }
public void should_configure_removing_attribute_event_to_ignore_special_tag() { // given HtmlSanitizerFactory factory = CreateFactory(); const string expectedHtml = "<a href=\"Special:redpage\"></a>"; // when IHtmlSanitizer sanitizer = factory.CreateHtmlSanitizer(); // then string actualHtml = sanitizer.Sanitize(expectedHtml); expectedHtml.ShouldBe(actualHtml); }
public IActionResult Post(Order order, [FromServices] IHtmlSanitizer sanitizer) { //if (!ModelState.IsValid) // return BadRequest(ModelState); // https://xss.ganss.org/ order.Note = sanitizer.Sanitize(order.Note); string email = User.FindFirstValue(ClaimTypes.Email); Trace.WriteLine($"Send email to {email} {order.Note}"); return(Ok(order)); }
public async Task SendMessage(string message, string recipientId) { if (string.IsNullOrEmpty(message)) { return; } string sanitizedMessage = htmlSanitizer.Sanitize(message); string userId = Context.UserIdentifier; await messageService.Create(sanitizedMessage, userId, recipientId); await Clients.User(recipientId).SendAsync("ReceiveMessage", sanitizedMessage, userId); await Clients.Caller.SendAsync("SendedMessage", sanitizedMessage); }
public async Task <IActionResult> CreateFolderAsync(Guid userId, string slug, Folder folder, CancellationToken cancellationToken) { var sanitisedFolder = new Folder { Name = _htmlSanitizer.Sanitize(folder.Name), Description = _htmlSanitizer.Sanitize(folder.Description) }; var folderId = await _folderService.CreateFolderAsync(userId, slug, sanitisedFolder, cancellationToken); return(Ok(folderId)); }
public void IndexPost([FromForm] UserLoginViewModel model) { var secret = "myveryimportnant_secret_key"; var salt = "ctis_salt_bae"; model.UserName = _sanitizer.Sanitize(model.UserName); if (ModelState.IsValid) { using (var sha = SHA512.Create()) { var hash = model.Password + secret + salt; var hashed = sha.ComputeHash(Encoding.UTF8.GetBytes(hash)); Debug.WriteLine(hashed); } Debug.WriteLine(model.UserName); } }
public async Task <string> SanitizePostBodyAsync(string body) { await ThreadingUtils.ContinueAtThreadPull(); var intermediate = _allowAllButNotExecutable.Sanitize(body); var document = new HtmlDocument(); document.LoadHtml(intermediate); var nodes = document.DocumentNode.SelectNodes("//img"); foreach (var node in nodes.NullToEmpty()) { var srcAttr = node.Attributes.Single(a => a.Name == "src"); var src = srcAttr.Value; src = await trySanitizeImage(src); if (src == null) { node.Remove(); } else { srcAttr.Value = src; const string ATTRIBUTE = "class"; if (node.Attributes.NotContains(a => a.Name == ATTRIBUTE)) { node.Attributes.Add(ATTRIBUTE, ""); } node.Attributes[ATTRIBUTE].Value += " rounded img-fluid"; } } var ms = new MemoryStream(); var writer = new StreamWriter(ms); document.Save(writer); writer.Flush(); ms.Position = 0; var sanitized = new StreamReader(ms) .ReadAllText() .Aggregate(); return(sanitized); }
/// <summary> /// Gets an IconModel containing the icon name and SvgString /// </summary> /// <param name="iconName"></param> /// <param name="iconPath"></param> /// <returns></returns> private IconModel CreateIconModel(string iconName, string iconPath) { try { var svgContent = System.IO.File.ReadAllText(iconPath); var sanitizedString = _htmlSanitizer.Sanitize(svgContent); var svg = new IconModel { Name = iconName, SvgString = sanitizedString }; return(svg); } catch { return(null); } }
public ActionResult <MessageReadDto> CreateMessage(MessageCreateDto messageCreateDto) { messageCreateDto.Text = _htmlSanitizer.Sanitize(_profanityFilter.CensorString(messageCreateDto.Text)); if (messageCreateDto.Text == "") { messageCreateDto.Text = "<prázdna po vyfiltrovaní>"; messageCreateDto.Deleted = true; } var messageModel = _mapper.Map <Message>(messageCreateDto); _onlineDOD.CreateMessage(messageModel); _onlineDOD.SaveChanges(); var messageReadDto = _mapper.Map <MessageReadDto>(messageModel); //Serilog.Log.Information($"[{this.Request.Host.Host}] POST /api/messages -> ID - {messageReadDto.Id}"); return(CreatedAtRoute(nameof(GetMessageById), new { Id = messageReadDto.Id }, messageReadDto)); }
public virtual StoryCreateResult Create(IUser byUser, string url, string title, string category, string description, string tags, string userIPAddress, string userAgent, string urlReferer, NameValueCollection serverVariables, Func <IStory, string> buildDetailUrl) { StoryCreateResult result = ValidateCreate(byUser, url, title, category, description, userIPAddress, userAgent); if (result == null) { if (_contentService.IsRestricted(url)) { result = new StoryCreateResult { ErrorMessage = "Podany url jest zablokowany." }; } } if (result == null) { using (IUnitOfWork unitOfWork = UnitOfWork.Begin()) { IStory alreadyExists = _storyRepository.FindByUrl(url); if (alreadyExists != null) { return(new StoryCreateResult { ErrorMessage = "Artykuł z danym url już istnieje.", DetailUrl = buildDetailUrl(alreadyExists) }); } ICategory storyCategory = _categoryRepository.FindByUniqueName(category); if (storyCategory == null) { return(new StoryCreateResult { ErrorMessage = "\"{0}\" nie istnieje.".FormatWith(category) }); } if (storyCategory.IsActive == false) { return(new StoryCreateResult { ErrorMessage = "\"{0}\" jest tylko do odczytu.".FormatWith(category) }); } StoryContent content = _contentService.Get(url); if (content == StoryContent.Empty) { return(new StoryCreateResult { ErrorMessage = "Podany Url wydaje się być wadliwy." }); } var splittedTags = tags.NullSafe().Split(','); if (splittedTags.Length == 1) //only one tag { var tag = splittedTags[0].Trim(); if (String.Compare(".net", tag, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare("c#", tag, StringComparison.OrdinalIgnoreCase) == 0) { return(new StoryCreateResult { ErrorMessage = "Proszę, pomyśl chwilę nad lepszymi tagami." }); } } if (splittedTags.Length == 2) //two tags, maybe not .net and C# { var tag1 = splittedTags[0].Trim(); var tag2 = splittedTags[1].Trim(); if ( (String.Compare(".net", tag1, StringComparison.OrdinalIgnoreCase) == 0 && String.Compare("c#", tag2, StringComparison.OrdinalIgnoreCase) == 0) || (String.Compare(".net", tag1, StringComparison.OrdinalIgnoreCase) == 0 && String.Compare("c#", tag2, StringComparison.OrdinalIgnoreCase) == 0) ) { return(new StoryCreateResult { ErrorMessage = "Tagi: .Net i C#. Srsly?" }); } } description = _htmlSanitizer.Sanitize(description); if (!_settings.AllowPossibleSpamStorySubmit && ShouldCheckSpamForUser(byUser)) { result = EnsureNotSpam <StoryCreateResult>(byUser, userIPAddress, userAgent, url, urlReferer, description, "social news", serverVariables, "Artykuł odrzucony: {0}, {1}".FormatWith(url, byUser), "Twój artykuł wydaje się być spamem."); if (result != null) { return(result); } } // If we are here which means story is not spam IStory story = _factory.CreateStory(storyCategory, byUser, userIPAddress, title.StripHtml(), description, url); _storyRepository.Add(story); // The Initial vote; story.Promote(story.CreatedAt, byUser, userIPAddress); // Capture the thumbnail, might speed up the thumbnail generation process _thumbnail.Capture(story.Url); // Subscribe comments by default story.SubscribeComment(byUser); AddTagsToContainers(tags, new ITagContainer[] { story, byUser }); string detailUrl = buildDetailUrl(story); if (_settings.AllowPossibleSpamStorySubmit && _settings.SendMailWhenPossibleSpamStorySubmitted && ShouldCheckSpamForUser(byUser)) { unitOfWork.Commit(); _spamProtection.IsSpam(CreateSpamCheckContent(byUser, userIPAddress, userAgent, url, urlReferer, description, "social news", serverVariables), (source, isSpam) => _spamPostprocessor.Process(source, isSpam, detailUrl, story)); } else { story.Approve(SystemTime.Now()); _eventAggregator.GetEvent <StorySubmitEvent>().Publish(new StorySubmitEventArgs(story, detailUrl)); unitOfWork.Commit(); } result = new StoryCreateResult { NewStory = story, DetailUrl = detailUrl }; } } return(result); }
public ValueTask <FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext ctx) { return(new ValueTask <FluidValue>(new StringValue(_sanitizer.Sanitize(input.ToStringValue())))); }
public IHtmlContent Sanitize(string source) { return(new HtmlString(_htmlSanitizer.Sanitize(source))); }
/// <summary> /// Creates a stoolball season and populates the <see cref="Season.SeasonId"/> /// </summary> /// <returns>The created season</returns> public async Task <Season> CreateSeason(Season season, Guid memberKey, string memberName) { if (season is null) { throw new ArgumentNullException(nameof(season)); } if (string.IsNullOrWhiteSpace(memberName)) { throw new ArgumentNullException(nameof(memberName)); } var auditableSeason = _copier.CreateAuditableCopy(season); auditableSeason.SeasonId = Guid.NewGuid(); auditableSeason.Introduction = _htmlSanitiser.Sanitize(auditableSeason.Introduction); auditableSeason.Results = _htmlSanitiser.Sanitize(auditableSeason.Results); using (var connection = _databaseConnectionFactory.CreateDatabaseConnection()) { connection.Open(); using (var transaction = connection.BeginTransaction()) { auditableSeason.SeasonRoute = $"{auditableSeason.Competition.CompetitionRoute}/{auditableSeason.FromYear}"; if (auditableSeason.UntilYear > auditableSeason.FromYear) { auditableSeason.SeasonRoute = $"{auditableSeason.SeasonRoute}-{auditableSeason.UntilYear.ToString(CultureInfo.InvariantCulture).Substring(2)}"; } // Get the most recent season, if any, to copy existing settings as defaults var previousSeason = await connection.QuerySingleOrDefaultAsync <Season>( $"SELECT TOP 1 SeasonId, ResultsTableType, EnableRunsScored, EnableRunsConceded FROM {Tables.Season} WHERE CompetitionId = @CompetitionId AND FromYear < @FromYear ORDER BY FromYear DESC", new { auditableSeason.Competition.CompetitionId, auditableSeason.FromYear }, transaction).ConfigureAwait(false); await connection.ExecuteAsync( $@"INSERT INTO {Tables.Season} (SeasonId, CompetitionId, FromYear, UntilYear, Introduction, EnableTournaments, EnableBonusOrPenaltyRuns, PlayersPerTeam, EnableLastPlayerBatsOn, ResultsTableType, EnableRunsScored, EnableRunsConceded, Results, SeasonRoute) VALUES (@SeasonId, @CompetitionId, @FromYear, @UntilYear, @Introduction, @EnableTournaments, @EnableBonusOrPenaltyRuns, @PlayersPerTeam, @EnableLastPlayerBatsOn, @ResultsTableType, @EnableRunsScored, @EnableRunsConceded, @Results, @SeasonRoute)", new { auditableSeason.SeasonId, auditableSeason.Competition.CompetitionId, auditableSeason.FromYear, auditableSeason.UntilYear, auditableSeason.Introduction, auditableSeason.EnableTournaments, auditableSeason.EnableBonusOrPenaltyRuns, auditableSeason.PlayersPerTeam, auditableSeason.EnableLastPlayerBatsOn, ResultsTableType = previousSeason?.ResultsTableType.ToString() ?? ResultsTableType.None.ToString(), EnableRunsScored = previousSeason?.EnableRunsScored ?? false, EnableRunsConceded = previousSeason?.EnableRunsConceded ?? false, auditableSeason.Results, auditableSeason.SeasonRoute }, transaction).ConfigureAwait(false); await InsertOverSets(auditableSeason, transaction).ConfigureAwait(false); foreach (var matchType in auditableSeason.MatchTypes) { await connection.ExecuteAsync($@"INSERT INTO {Tables.SeasonMatchType} (SeasonMatchTypeId, SeasonId, MatchType) VALUES (@SeasonMatchTypeId, @SeasonId, @MatchType)", new { SeasonMatchTypeId = Guid.NewGuid(), auditableSeason.SeasonId, MatchType = matchType.ToString() }, transaction).ConfigureAwait(false); } // Copy points rules from the most recent season if (previousSeason != null) { auditableSeason.PointsRules = (await connection.QueryAsync <PointsRule>( $@"SELECT MatchResultType, HomePoints, AwayPoints FROM { Tables.PointsRule } WHERE SeasonId = @SeasonId", new { previousSeason.SeasonId }, transaction).ConfigureAwait(false)).ToList(); } // If there are none, start with some default points rules if (auditableSeason.PointsRules.Count == 0) { auditableSeason.PointsRules.AddRange(new PointsRule[] { new PointsRule { MatchResultType = MatchResultType.HomeWin, HomePoints = 2, AwayPoints = 0 }, new PointsRule { MatchResultType = MatchResultType.AwayWin, HomePoints = 0, AwayPoints = 2 }, new PointsRule { MatchResultType = MatchResultType.HomeWinByForfeit, HomePoints = 2, AwayPoints = 0 }, new PointsRule { MatchResultType = MatchResultType.AwayWinByForfeit, HomePoints = 0, AwayPoints = 2 }, new PointsRule { MatchResultType = MatchResultType.Tie, HomePoints = 1, AwayPoints = 1 }, new PointsRule { MatchResultType = MatchResultType.Cancelled, HomePoints = 1, AwayPoints = 1 }, new PointsRule { MatchResultType = MatchResultType.AbandonedDuringPlayAndCancelled, HomePoints = 1, AwayPoints = 1 } }); } foreach (var pointsRule in auditableSeason.PointsRules) { pointsRule.PointsRuleId = Guid.NewGuid(); await connection.ExecuteAsync($@"INSERT INTO { Tables.PointsRule } (PointsRuleId, SeasonId, MatchResultType, HomePoints, AwayPoints) VALUES (@PointsRuleId, @SeasonId, @MatchResultType, @HomePoints, @AwayPoints)", new { pointsRule.PointsRuleId, auditableSeason.SeasonId, pointsRule.MatchResultType, pointsRule.HomePoints, pointsRule.AwayPoints }, transaction).ConfigureAwait(false); } // Copy teams from the most recent season, where the teams did not withdraw and were still active in the season being added if (previousSeason != null) { var teamIds = await connection.QueryAsync <Guid>( $@"SELECT DISTINCT t.TeamId FROM { Tables.SeasonTeam } st INNER JOIN { Tables.Team } t ON st.TeamId = t.TeamId INNER JOIN { Tables.TeamVersion } tv ON t.TeamId = tv.TeamId WHERE st.SeasonId = @SeasonId AND st.WithdrawnDate IS NULL AND (tv.UntilDate IS NULL OR tv.UntilDate <= @FromDate)", new { previousSeason.SeasonId, FromDate = new DateTime(auditableSeason.FromYear, 12, 31).ToUniversalTime() }, transaction).ConfigureAwait(false); foreach (var teamId in teamIds) { auditableSeason.Teams.Add(new TeamInSeason { Team = new Team { TeamId = teamId } }); await connection.ExecuteAsync($@"INSERT INTO { Tables.SeasonTeam } (SeasonTeamId, SeasonId, TeamId) VALUES (@SeasonTeamId, @SeasonId, @TeamId)", new { SeasonTeamId = Guid.NewGuid(), auditableSeason.SeasonId, teamId }, transaction).ConfigureAwait(false); } } var redacted = _copier.CreateRedactedCopy(auditableSeason); await _auditRepository.CreateAudit(new AuditRecord { Action = AuditAction.Create, MemberKey = memberKey, ActorName = memberName, EntityUri = auditableSeason.EntityUri, State = JsonConvert.SerializeObject(auditableSeason), RedactedState = JsonConvert.SerializeObject(redacted), AuditDate = DateTime.UtcNow }, transaction).ConfigureAwait(false); transaction.Commit(); _logger.Info(GetType(), LoggingTemplates.Created, redacted, memberName, memberKey, GetType(), nameof(SqlServerSeasonRepository.CreateSeason)); } } return(auditableSeason); }
public static string Sanitize(string html) => Sanitizer.Sanitize(html);
public string Sanitize(string html) { return(_sanitizer.Sanitize(html)); }