示例#1
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);
        }
示例#2
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);
        }
 public SanitizerService()
 {
     this.sanitizer = new HtmlSanitizer();
     this.sanitizer.AllowedTags.Clear();
     this.sanitizer.AllowedCssProperties.Clear();
 }
示例#4
0
 public ProductDetailsViewModel()
 {
     this.sanitizer = new HtmlSanitizer();
     this.sanitizer.AllowedTags.Add("iframe");
 }
示例#5
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);
        }
示例#6
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);
        }
示例#7
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);
        }
示例#8
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);
        }
示例#9
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);
        }
示例#10
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);
        }
示例#11
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);
        }
示例#12
0
    private void CustomServices(IServiceCollection services)
    {
        services.AddSingleton <FFmpegPlaybackSettingsCalculator>();
        services.AddSingleton <IPlexSecretStore, PlexSecretStore>();
        services.AddSingleton <IPlexTvApiClient, PlexTvApiClient>(); // TODO: does this need to be singleton?
        services.AddSingleton <ITraktApiClient, TraktApiClient>();
        services.AddSingleton <IEntityLocker, EntityLocker>();
        services.AddSingleton <ISearchIndex, SearchIndex>();
        services.AddSingleton <IFFmpegSegmenterService, FFmpegSegmenterService>();
        services.AddSingleton <ITempFilePool, TempFilePool>();
        services.AddSingleton <IHlsPlaylistFilter, HlsPlaylistFilter>();
        AddChannel <IBackgroundServiceRequest>(services);
        AddChannel <IPlexBackgroundServiceRequest>(services);
        AddChannel <IJellyfinBackgroundServiceRequest>(services);
        AddChannel <IEmbyBackgroundServiceRequest>(services);
        AddChannel <IFFmpegWorkerRequest>(services);
        AddChannel <ISubtitleWorkerRequest>(services);

        services.AddScoped <IFFmpegVersionHealthCheck, FFmpegVersionHealthCheck>();
        services.AddScoped <IFFmpegReportsHealthCheck, FFmpegReportsHealthCheck>();
        services.AddScoped <IHardwareAccelerationHealthCheck, HardwareAccelerationHealthCheck>();
        services.AddScoped <IMovieMetadataHealthCheck, MovieMetadataHealthCheck>();
        services.AddScoped <IEpisodeMetadataHealthCheck, EpisodeMetadataHealthCheck>();
        services.AddScoped <IZeroDurationHealthCheck, ZeroDurationHealthCheck>();
        services.AddScoped <IFileNotFoundHealthCheck, FileNotFoundHealthCheck>();
        services.AddScoped <IUnavailableHealthCheck, UnavailableHealthCheck>();
        services.AddScoped <IVaapiDriverHealthCheck, VaapiDriverHealthCheck>();
        services.AddScoped <IErrorReportsHealthCheck, ErrorReportsHealthCheck>();
        services.AddScoped <IHealthCheckService, HealthCheckService>();

        services.AddScoped <IChannelRepository, ChannelRepository>();
        services.AddScoped <IFFmpegProfileRepository, FFmpegProfileRepository>();
        services.AddScoped <IMediaSourceRepository, MediaSourceRepository>();
        services.AddScoped <IMediaItemRepository, MediaItemRepository>();
        services.AddScoped <IMediaCollectionRepository, MediaCollectionRepository>();
        services.AddScoped <IConfigElementRepository, ConfigElementRepository>();
        services.AddScoped <ITelevisionRepository, TelevisionRepository>();
        services.AddScoped <ISearchRepository, SearchRepository>();
        services.AddScoped <IMovieRepository, MovieRepository>();
        services.AddScoped <IArtistRepository, ArtistRepository>();
        services.AddScoped <IMusicVideoRepository, MusicVideoRepository>();
        services.AddScoped <IOtherVideoRepository, OtherVideoRepository>();
        services.AddScoped <ISongRepository, SongRepository>();
        services.AddScoped <ILibraryRepository, LibraryRepository>();
        services.AddScoped <IMetadataRepository, MetadataRepository>();
        services.AddScoped <IArtworkRepository, ArtworkRepository>();
        services.AddScoped <IFFmpegLocator, FFmpegLocator>();
        services.AddScoped <ILocalMetadataProvider, LocalMetadataProvider>();
        services.AddScoped <IFallbackMetadataProvider, FallbackMetadataProvider>();
        services.AddScoped <ILocalStatisticsProvider, LocalStatisticsProvider>();
        services.AddScoped <ILocalSubtitlesProvider, LocalSubtitlesProvider>();
        services.AddScoped <IPlayoutBuilder, PlayoutBuilder>();
        services.AddScoped <IImageCache, ImageCache>();
        services.AddScoped <ILocalFileSystem, LocalFileSystem>();
        services.AddScoped <IMovieFolderScanner, MovieFolderScanner>();
        services.AddScoped <ITelevisionFolderScanner, TelevisionFolderScanner>();
        services.AddScoped <IMusicVideoFolderScanner, MusicVideoFolderScanner>();
        services.AddScoped <IOtherVideoFolderScanner, OtherVideoFolderScanner>();
        services.AddScoped <ISongFolderScanner, SongFolderScanner>();
        services.AddScoped <IPlexMovieLibraryScanner, PlexMovieLibraryScanner>();
        services.AddScoped <IPlexTelevisionLibraryScanner, PlexTelevisionLibraryScanner>();
        services.AddScoped <IPlexServerApiClient, PlexServerApiClient>();
        services.AddScoped <IPlexMovieRepository, PlexMovieRepository>();
        services.AddScoped <IPlexTelevisionRepository, PlexTelevisionRepository>();
        services.AddScoped <IJellyfinMovieLibraryScanner, JellyfinMovieLibraryScanner>();
        services.AddScoped <IJellyfinTelevisionLibraryScanner, JellyfinTelevisionLibraryScanner>();
        services.AddScoped <IJellyfinCollectionScanner, JellyfinCollectionScanner>();
        services.AddScoped <IJellyfinApiClient, JellyfinApiClient>();
        services.AddScoped <IJellyfinPathReplacementService, JellyfinPathReplacementService>();
        services.AddScoped <IJellyfinTelevisionRepository, JellyfinTelevisionRepository>();
        services.AddScoped <IJellyfinCollectionRepository, JellyfinCollectionRepository>();
        services.AddScoped <IJellyfinMovieRepository, JellyfinMovieRepository>();
        services.AddScoped <IEmbyApiClient, EmbyApiClient>();
        services.AddScoped <IEmbyMovieLibraryScanner, EmbyMovieLibraryScanner>();
        services.AddScoped <IEmbyTelevisionLibraryScanner, EmbyTelevisionLibraryScanner>();
        services.AddScoped <IEmbyCollectionScanner, EmbyCollectionScanner>();
        services.AddScoped <IEmbyPathReplacementService, EmbyPathReplacementService>();
        services.AddScoped <IEmbyTelevisionRepository, EmbyTelevisionRepository>();
        services.AddScoped <IEmbyCollectionRepository, EmbyCollectionRepository>();
        services.AddScoped <IEmbyMovieRepository, EmbyMovieRepository>();
        services.AddScoped <IRuntimeInfo, RuntimeInfo>();
        services.AddScoped <IPlexPathReplacementService, PlexPathReplacementService>();
        services.AddScoped <IFFmpegStreamSelector, FFmpegStreamSelector>();

        services.AddScoped <IFFmpegProcessService, FFmpegLibraryProcessService>();
        services.AddScoped <FFmpegProcessService>();

        services.AddScoped <ISongVideoGenerator, SongVideoGenerator>();
        services.AddScoped <HlsSessionWorker>();
        services.AddScoped <IGitHubApiClient, GitHubApiClient>();
        services.AddScoped <IHtmlSanitizer, HtmlSanitizer>(
            _ =>
        {
            var sanitizer = new HtmlSanitizer();
            sanitizer.AllowedAttributes.Add("class");
            return(sanitizer);
        });
        services.AddScoped <IJellyfinSecretStore, JellyfinSecretStore>();
        services.AddScoped <IEmbySecretStore, EmbySecretStore>();
        services.AddScoped <IEpisodeNfoReader, EpisodeNfoReader>();

        // services.AddTransient(typeof(IRequestHandler<,>), typeof(GetRecentLogEntriesHandler<>));

        services.AddHostedService <EndpointValidatorService>();
        services.AddHostedService <DatabaseMigratorService>();
        services.AddHostedService <CacheCleanerService>();
        services.AddHostedService <ResourceExtractorService>();
        services.AddHostedService <PlatformSettingsService>();
        services.AddHostedService <EmbyService>();
        services.AddHostedService <JellyfinService>();
        services.AddHostedService <PlexService>();
        services.AddHostedService <FFmpegLocatorService>();
        services.AddHostedService <WorkerService>();
        services.AddHostedService <SchedulerService>();
        services.AddHostedService <FFmpegWorkerService>();
        services.AddHostedService <SubtitleWorkerService>();
    }
 private static void FlattenTag(this HtmlSanitizer htmlSanitizer, string tagName)
 {
     htmlSanitizer.Tag(tagName).Operation(SanitizerOperation.FlattenTag);
 }
示例#14
0
        public void TestHtmlSanitize()
        {
            var html = @"
<html>
<head>
    this element will be removed
</head>
<body onload='hack_my_website()'>
    <script src='Blahblahblah'></script>
    <link rel='stylesheet' href=Blahblahblah' type='text/css' />
    <div src='javascript:script()'>
        <input onclick='stuff()'></input>
        <img src='src path'>
    </div>
    <div>
        some text
        script
        some text
    </div>
    <div class='expression'>
        <span>
            <p>some text</p>
            <textarea>some text</textarea>
        </span>
    </div>
    <table class='table'>
        <thead>
            <th></th>
        </thead>
        <tbody>
            <tr>
                <td></td>
            </tr>
        </tbody>
        <tfoot></tfoot>
    </table>
    <p class=MsoNormal><a name='_MailEndCompose'><o:p>&nbsp;</o:p></a></p>
    <span style='mso-bookmark:_MailEndCompose'></span>
    <div style ='border:none;border-top:solid #E1E1E1 1.0pt;padding:3.0pt 0cm 0cm'></div>
</body>
</html>";

            var expectedResult = @"
<html>
<body>
    <div>
        <input>
        <img src='src path'>
    </div>
    <div>
    </div>
    <div>
        <span>
            <p>some text</p>
            <textarea>some text</textarea>
        </span>
    </div>
    <table class='table'>
        <thead>
            <th></th>
        </thead>
        <tbody>
            <tr>
                <td></td>
            </tr>
        </tbody>
        <tfoot></tfoot>
    </table>
    <p class='MsoNormal'><a name='_MailEndCompose'></a></p>
    <span style='mso-bookmark:_MailEndCompose'></span>
    <div style ='border:none;border-top:solid #E1E1E1 1.0pt;padding:3.0pt 0cm 0cm'></div>
</body>
</html>";

            var sanitize = new HtmlSanitizer();
            var result   = sanitize.Sanitize(html);

            result         = result.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "'").Replace(" ", "");
            expectedResult = expectedResult.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "'").Replace(" ", "");
            Assert.True(result == expectedResult);
        }
示例#15
0
        public static string CleanHtml(string html)
        {
            var sanitizer = new HtmlSanitizer();

            return(sanitizer.Sanitize(html));
        }
示例#16
0
        public override void Compose(Composition composition)
        {
            base.Compose(composition);

            composition.Register <UmbracoInjectedModule>();

            composition.RegisterUnique <IHttpContextAccessor, AspNetHttpContextAccessor>(); // required for hybrid accessors

            composition.ComposeWebMappingProfiles();

            //register the install components
            //NOTE: i tried to not have these registered if we weren't installing or upgrading but post install when the site restarts
            //it still needs to use the install controller so we can't do that
            composition.ComposeInstaller();

            // register membership stuff
            composition.Register(factory => Core.Security.MembershipProviderExtensions.GetMembersMembershipProvider());
            composition.Register(factory => Roles.Enabled ? Roles.Provider : new MembersRoleProvider(factory.GetInstance <IMemberService>()));
            composition.Register <MembershipHelper>(Lifetime.Request);
            composition.Register <IPublishedMemberCache>(factory => factory.GetInstance <UmbracoContext>().PublishedSnapshot.Members);

            // register accessors for cultures
            composition.RegisterUnique <IDefaultCultureAccessor, DefaultCultureAccessor>();
            composition.RegisterUnique <IVariationContextAccessor, HybridVariationContextAccessor>();

            // register the http context and umbraco context accessors
            // we *should* use the HttpContextUmbracoContextAccessor, however there are cases when
            // we have no http context, eg when booting Umbraco or in background threads, so instead
            // let's use an hybrid accessor that can fall back to a ThreadStatic context.
            composition.RegisterUnique <IUmbracoContextAccessor, HybridUmbracoContextAccessor>();

            // register the umbraco context factory
            composition.RegisterUnique <IUmbracoContextFactory, UmbracoContextFactory>();

            // register a per-request HttpContextBase object
            // is per-request so only one wrapper is created per request
            composition.Register <HttpContextBase>(factory => new HttpContextWrapper(factory.GetInstance <IHttpContextAccessor>().HttpContext), Lifetime.Request);

            // register the published snapshot accessor - the "current" published snapshot is in the umbraco context
            composition.RegisterUnique <IPublishedSnapshotAccessor, UmbracoContextPublishedSnapshotAccessor>();

            // we should stop injecting UmbracoContext and always inject IUmbracoContextAccessor, however at the moment
            // there are tons of places (controllers...) which require UmbracoContext in their ctor - so let's register
            // a way to inject the UmbracoContext - DO NOT register this as Lifetime.Request since LI will dispose the context
            // in it's own way but we don't want that to happen, we manage its lifetime ourselves.
            composition.Register(factory => factory.GetInstance <IUmbracoContextAccessor>().UmbracoContext);
            composition.RegisterUnique <IUmbracoTreeSearcherFields, UmbracoTreeSearcherFields>();
            composition.Register <IPublishedContentQuery>(factory =>
            {
                var umbCtx = factory.GetInstance <IUmbracoContextAccessor>();
                return(new PublishedContentQuery(umbCtx.UmbracoContext.PublishedSnapshot, factory.GetInstance <IVariationContextAccessor>()));
            }, Lifetime.Request);
            composition.Register <ITagQuery, TagQuery>(Lifetime.Request);

            composition.RegisterUnique <ITemplateRenderer, TemplateRenderer>();
            composition.RegisterUnique <IMacroRenderer, MacroRenderer>();
            composition.RegisterUnique <IUmbracoComponentRenderer, UmbracoComponentRenderer>();

            composition.RegisterUnique <HtmlLocalLinkParser>();
            composition.RegisterUnique <HtmlUrlParser>();
            composition.RegisterUnique <HtmlImageSourceParser>();
            composition.RegisterUnique <RichTextEditorPastedImages>();
            composition.RegisterUnique <PropertyEditors.ValueConverters.BlockEditorConverter>();

            // register the umbraco helper - this is Transient! very important!
            // also, if not level.Run, we cannot really use the helper (during upgrade...)
            // so inject a "void" helper (not exactly pretty but...)
            if (composition.RuntimeState.Level == RuntimeLevel.Run)
            {
                composition.Register <UmbracoHelper>(factory =>
                {
                    var umbCtx = factory.GetInstance <UmbracoContext>();
                    return(new UmbracoHelper(umbCtx.IsFrontEndUmbracoRequest ? umbCtx.PublishedRequest?.PublishedContent : null,
                                             factory.GetInstance <ITagQuery>(), factory.GetInstance <ICultureDictionaryFactory>(),
                                             factory.GetInstance <IUmbracoComponentRenderer>(), factory.GetInstance <IPublishedContentQuery>(),
                                             factory.GetInstance <MembershipHelper>()));
                });
            }
            else
            {
                composition.Register(_ => new UmbracoHelper());
            }

            // register distributed cache
            composition.RegisterUnique(f => new DistributedCache());

            composition.RegisterUnique <RoutableDocumentFilter>();

            // replace some services
            composition.RegisterUnique <IEventMessagesFactory, DefaultEventMessagesFactory>();
            composition.RegisterUnique <IEventMessagesAccessor, HybridEventMessagesAccessor>();
            composition.RegisterUnique <ITreeService, TreeService>();
            composition.RegisterUnique <ISectionService, SectionService>();
            composition.RegisterUnique <IDashboardService, DashboardService>();
            composition.RegisterUnique <IIconService, IconService>();
            composition.Register <IHtmlSanitizer>(_ =>
            {
                var sanitizer = new HtmlSanitizer();
                sanitizer.AllowedAttributes.UnionWith(Umbraco.Core.Constants.SvgSanitizer.Attributes);
                sanitizer.AllowedCssProperties.UnionWith(Umbraco.Core.Constants.SvgSanitizer.Attributes);
                sanitizer.AllowedTags.UnionWith(Umbraco.Core.Constants.SvgSanitizer.Tags);
                return(sanitizer);
            }, Lifetime.Singleton);

            composition.RegisterUnique <IExamineManager>(factory => ExamineManager.Instance);

            // configure the container for web
            composition.ConfigureForWeb();

            composition
            .ComposeUmbracoControllers(GetType().Assembly)
            .SetDefaultRenderMvcController <RenderMvcController>();    // default controller for template views

            composition.SearchableTrees()
            .Add(() => composition.TypeLoader.GetTypes <ISearchableTree>());

            composition.Register <UmbracoTreeSearcher>(Lifetime.Request);

            composition.EditorValidators()
            .Add(() => composition.TypeLoader.GetTypes <IEditorValidator>());

            composition.TourFilters();

            composition.RegisterUnique <UmbracoFeatures>();

            composition.Actions()
            .Add(() => composition.TypeLoader.GetTypes <IAction>());

            //we need to eagerly scan controller types since they will need to be routed
            composition.WithCollectionBuilder <SurfaceControllerTypeCollectionBuilder>()
            .Add(composition.TypeLoader.GetSurfaceControllers());
            var umbracoApiControllerTypes = composition.TypeLoader.GetUmbracoApiControllers().ToList();

            composition.WithCollectionBuilder <UmbracoApiControllerTypeCollectionBuilder>()
            .Add(umbracoApiControllerTypes);

            // both TinyMceValueConverter (in Core) and RteMacroRenderingValueConverter (in Web) will be
            // discovered when CoreBootManager configures the converters. We HAVE to remove one of them
            // here because there cannot be two converters for one property editor - and we want the full
            // RteMacroRenderingValueConverter that converts macros, etc. So remove TinyMceValueConverter.
            // (the limited one, defined in Core, is there for tests) - same for others
            composition.PropertyValueConverters()
            .Remove <TinyMceValueConverter>()
            .Remove <TextStringValueConverter>()
            .Remove <MarkdownEditorValueConverter>();

            // add all known factories, devs can then modify this list on application
            // startup either by binding to events or in their own global.asax
            composition.FilteredControllerFactory()
            .Append <RenderControllerFactory>();

            composition.UrlProviders()
            .Append <AliasUrlProvider>()
            .Append <DefaultUrlProvider>();

            composition.MediaUrlProviders()
            .Append <DefaultMediaUrlProvider>();

            composition.RegisterUnique <IImageUrlGenerator, ImageProcessorImageUrlGenerator>();

            composition.RegisterUnique <IContentLastChanceFinder, ContentFinderByConfigured404>();

            composition.ContentFinders()
            // all built-in finders in the correct order,
            // devs can then modify this list on application startup
            .Append <ContentFinderByPageIdQuery>()
            .Append <ContentFinderByUrl>()
            .Append <ContentFinderByIdPath>()
            //.Append<ContentFinderByUrlAndTemplate>() // disabled, this is an odd finder
            .Append <ContentFinderByUrlAlias>();
            //only append ContentFinderByRedirectUrl if RedirectUrlTracking is not disabled
            if (composition.Configs.Settings().WebRouting.DisableRedirectUrlTracking == false)
            {
                composition.ContentFinders().Append <ContentFinderByRedirectUrl>();
            }

            composition.RegisterUnique <ISiteDomainHelper, SiteDomainHelper>();

            composition.RegisterUnique <ICultureDictionaryFactory, DefaultCultureDictionaryFactory>();

            // register *all* checks, except those marked [HideFromTypeFinder] of course
            composition.HealthChecks()
            .Add(() => composition.TypeLoader.GetTypes <HealthCheck.HealthCheck>());

            composition.WithCollectionBuilder <HealthCheckNotificationMethodCollectionBuilder>()
            .Add(() => composition.TypeLoader.GetTypes <HealthCheck.NotificationMethods.IHealthCheckNotificationMethod>());

            // auto-register views
            composition.RegisterAuto(typeof(UmbracoViewPage <>));

            // register published router
            composition.RegisterUnique <IPublishedRouter, PublishedRouter>();
            composition.Register(_ => Current.Configs.Settings().WebRouting);

            // register preview SignalR hub
            composition.RegisterUnique(_ => GlobalHost.ConnectionManager.GetHubContext <PreviewHub>());

            // register properties fallback
            composition.RegisterUnique <IPublishedValueFallback, PublishedValueFallback>();

            // register known content apps
            composition.ContentApps()
            .Append <ListViewContentAppFactory>()
            .Append <ContentEditorContentAppFactory>()
            .Append <ContentInfoContentAppFactory>()
            .Append <ContentTypeDesignContentAppFactory>()
            .Append <ContentTypeListViewContentAppFactory>()
            .Append <ContentTypePermissionsContentAppFactory>()
            .Append <ContentTypeTemplatesContentAppFactory>();

            // register back office sections in the order we want them rendered
            composition.Sections()
            .Append <ContentSection>()
            .Append <MediaSection>()
            .Append <SettingsSection>()
            .Append <PackagesSection>()
            .Append <UsersSection>()
            .Append <MembersSection>()
            .Append <FormsSection>()
            .Append <TranslationSection>();

            // register core CMS dashboards and 3rd party types - will be ordered by weight attribute & merged with package.manifest dashboards
            composition.Dashboards()
            .Add(composition.TypeLoader.GetTypes <IDashboard>());

            // register back office trees
            // the collection builder only accepts types inheriting from TreeControllerBase
            // and will filter out those that are not attributed with TreeAttribute
            composition.Trees()
            .AddTreeControllers(umbracoApiControllerTypes.Where(x => typeof(TreeControllerBase).IsAssignableFrom(x)));

            // register OEmbed providers - no type scanning - all explicit opt-in of adding types
            // note: IEmbedProvider is not IDiscoverable - think about it if going for type scanning
            composition.OEmbedProviders()
            .Append <YouTube>()
            .Append <Twitter>()
            .Append <Vimeo>()
            .Append <DailyMotion>()
            .Append <Flickr>()
            .Append <Slideshare>()
            .Append <Kickstarter>()
            .Append <GettyImages>()
            .Append <Ted>()
            .Append <Soundcloud>()
            .Append <Issuu>()
            .Append <Hulu>()
            .Append <Giphy>();


            // replace with web implementation
            composition.RegisterUnique <IPublishedSnapshotRebuilder, Migrations.PostMigrations.PublishedSnapshotRebuilder>();
        }
示例#17
0
 public void Sanitize(HtmlSanitizer sanitizer)
 {
     Email    = sanitizer.Sanitize(Email);
     Password = sanitizer.Sanitize(Password);
 }
示例#18
0
        public static HtmlString Sanitize(this string html)
        {
            // Run it through Markdown first
            var md = new Markdown();

            html = md.Transform(html);

            // Add links to URLs that aren't "properly" linked in a markdown way
            var regex = new Regex(@"(^|\s|>|;)(https?|ftp)(:\/\/[-A-Z0-9+&@#\/%?=~_|\[\]\(\)!:,\.;]*[-A-Z0-9+&@#\/%=~_|\[\]])($|\W)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            var linkedHtml = regex.Replace(html, "$1<a href=\"$2$3\">$2$3</a>$4").Replace("href=\"www", "href=\"http://www");

            var scriptRegex        = new Regex("<script.*?</script>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            var scriptRegexMatches = scriptRegex.Matches(linkedHtml);

            for (var i = 0; i < scriptRegexMatches.Count; i++)
            {
                linkedHtml = linkedHtml.Replace(scriptRegexMatches[i].Value, $"<pre>{HttpContext.Current.Server.HtmlEncode(scriptRegexMatches[i].Value)}</pre>");
            }

            html = linkedHtml;

            // Linkify images if they are shown as resized versions (only relevant for new Markdown comments)
            var doc = new HtmlDocument();

            doc.LoadHtml(html);

            var root = doc.DocumentNode;

            if (root != null)
            {
                var images = root.SelectNodes("//img");
                if (images != null)
                {
                    foreach (var image in images)
                    {
                        var src    = image.GetAttributeValue("src", "");
                        var orgSrc = src.Replace("rs/", "");

                        if (src == orgSrc || image.ParentNode.Name == "a")
                        {
                            continue;
                        }

                        var a = doc.CreateElement("a");
                        a.SetAttributeValue("href", orgSrc);
                        a.SetAttributeValue("target", "_blank");

                        a.AppendChild(image.Clone());

                        image.ParentNode.ReplaceChild(a, image);
                    }
                }

                // Any links not going to an "approved" domain need to be marked as nofollow
                var links = root.SelectNodes("//a");
                if (links != null)
                {
                    foreach (var link in links)
                    {
                        if (link.Attributes["href"] != null && (SpamChecker.CountValidLinks(link.Attributes["href"].Value, 0) == 0))
                        {
                            if (link.Attributes["rel"] != null)
                            {
                                link.Attributes.Remove("rel");
                            }
                            link.Attributes.Add("rel", "noopener");
                        }
                    }
                }

                // Remove styles from all elements
                var elementsWithStyleAttribute = root.SelectNodes("//@style");
                if (elementsWithStyleAttribute != null)
                {
                    foreach (var element in elementsWithStyleAttribute)
                    {
                        element.Attributes.Remove("style");
                    }
                }

                using (var writer = new StringWriter())
                {
                    doc.Save(writer);
                    html = writer.ToString();
                }
            }

            var sanitizer = new HtmlSanitizer();
            var sanitized = sanitizer.Sanitize(html);

            return(new HtmlString(sanitized));
        }
示例#19
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);
        }
示例#20
0
 public QuestionHandler(Database database, MarkdownPipeline markdownPipeline, NotificationBuilder notificationBuilder, HtmlSanitizer htmlSanitizer)
 {
     this.database            = database;
     this.markdownPipeline    = markdownPipeline;
     this.notificationBuilder = notificationBuilder;
     sanitizer = htmlSanitizer;
 }
示例#21
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);
        }
示例#22
0
 public static string SanitizeDoc(this HtmlSanitizer htmlSanitizer, IHtmlDocument doc)
 {
     return(doc.Body.ChildNodes.ToHtml(Sanitizer.OutputFormatter));
 }
示例#23
0
 public Sanitizer(SanitizerOptions options)
 {
     this.options  = options;
     htmlSanitizer = new HtmlSanitizer();
     ConfigureHtmlSanitizer();
 }
 public CommentViewModel()
 {
     this.sanitizer = new HtmlSanitizer();
 }
示例#25
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);
        }
 public HtmlSanitizerActionFilterImpl(HtmlSanitizer htmlSanitizer)
 {
     _htmlSanitizer = htmlSanitizer;
 }
示例#27
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);
        }
示例#28
0
 public BlogsController(BlogsContext blogsContext)
 {
     _blogsContext  = blogsContext;
     _htmlSanitizer = new HtmlSanitizer();
 }
示例#29
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);
        }
示例#30
0
        public static string SanitizeHtmlInString(string source)
        {
            StringCollection sc   = new StringCollection();
            string           temp = source;

            // get rid of unnecessary tag spans (comments and title)
            sc.Add(@"<!--(w|W)+?-->");
            sc.Add(@"<title>(w|W)+?</title>");

            // Get rid of classes and styles
            sc.Add(@"s?class=w+");
            sc.Add(@"s+style='[^']+'");

            // Get rid of unnecessary tags
            sc.Add(@"<(meta|link|/?o:|/?style|/?std|/?head|/?html|body|/?body)[^>]*?>");

            // Get rid of empty paragraph tags
            sc.Add(@"(<[^>]+>)+&nbsp;(</w+>)+");

            // remove bizarre v: element attached to <img> tag
            sc.Add(@"s+v:w+=""[^""]+""");

            // remove extra lines
            sc.Add(@"(nr){2,}");

            foreach (string s in sc)
            {
                source = Regex.Replace(source, s, "", RegexOptions.IgnoreCase);
            }

            if (String.IsNullOrWhiteSpace(source))
            {
                Logging.LogError("Following string could not be stripped of Word HTML: " + temp);
                return("Invalid HTML in Source String");
            }

            var sanitizer = new HtmlSanitizer();

            sanitizer.Tag("h1").RemoveEmpty();
            sanitizer.Tag("h2").RemoveEmpty();
            sanitizer.Tag("h3").RemoveEmpty();
            sanitizer.Tag("h4").RemoveEmpty();
            sanitizer.Tag("h5").RemoveEmpty();
            sanitizer.Tag("strong").RemoveEmpty();
            sanitizer.Tag("b").Rename("strong").RemoveEmpty();
            sanitizer.Tag("i").RemoveEmpty();
            sanitizer.Tag("em");
            sanitizer.Tag("br");
            sanitizer.Tag("p").RemoveEmpty();
            sanitizer.Tag("div").NoAttributes(SanitizerOperation.FlattenTag);
            sanitizer.Tag("span").RemoveEmpty();
            sanitizer.Tag("ul");
            sanitizer.Tag("ol");
            sanitizer.Tag("li");
            sanitizer.Tag("a").SetAttribute("rel", "nofollow")
            .CheckAttribute("href", HtmlSanitizerCheckType.Url)
            .RemoveEmpty();

            string cleanHtml = sanitizer.Sanitize(source);

            if (!String.IsNullOrWhiteSpace(cleanHtml))
            {
                return(cleanHtml.Trim());
            }

            //Logging.LogError("Following string could not be sanitized: " + source);
            return("Invalid HTML in Source String");
        }
示例#31
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);
 }
示例#32
0
        public string SanitizeHTML(string html)
        {
            HtmlSanitizer htmlSanitizer = new HtmlSanitizer();

            return(htmlSanitizer.Sanitize(html));
        }
示例#33
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);
        }
示例#34
0
 public ReceptiController(IReceptRepo receptRepo, IHostingEnvironment hostingEnvironment)
 {
     _receptRepo         = receptRepo;
     _hostingEnvironment = hostingEnvironment;
     _htmlSanitizer      = new HtmlSanitizer();
 }
示例#35
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);
        }
 public HtmlSanitizerService(HtmlSanitizer htmlSanitizer)
 {
     this.htmlSanitizer = htmlSanitizer;
 }
示例#37
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);
        }
示例#38
0
        public List <string> GenerateCodeList(bool extractfiles,
                                              Dictionary <string, List <string> > checkClassNamesDic,
                                              string path,
                                              LanguageEnum lan,
                                              LanAttributes prop,
                                              string namespaceMapping)
        {
            StringBuilder codeBuilder = new StringBuilder();
            List <string> codeList    = new List <string>();
            //goes for lan c# and java

            StringBuilder cSharpUsings = new StringBuilder()
            {
                Capacity = 0,
                Length   = 0
            };

            cSharpUsings.AppendLine("using System;");
            cSharpUsings.AppendLine("using System.Collections.Generic;");

            StringBuilder javaUsings = new StringBuilder()
            {
                Capacity = 0,
                Length   = 0
            };

            javaUsings.AppendLine("import java.util.Date;");
            javaUsings.AppendLine("import java.util.ArrayList;");

            ///Meaning that we have chosen Datacontracts and DataMembers

            switch (prop)
            {
            case LanAttributes.None:
                break;

            case LanAttributes.DataContract:
                cSharpUsings.AppendLine("using System.Runtime.Serialization;");
                break;

            case LanAttributes.Json:
                cSharpUsings.AppendLine("using Newtonsoft.Json;");
                break;
            }

            string lanClassDef    = string.Empty;
            string lanbracesStart = string.Empty;
            string lanBrracesEnd  = string.Empty;

            switch (lan)
            {
            case LanguageEnum.CSharp:
                //using for C# class
                lanClassDef    = "  public class";
                lanbracesStart = "  {";
                lanBrracesEnd  = "  }";

                break;

            case LanguageEnum.PHP:
                //using for PHP class
                lanClassDef    = "  class";
                lanbracesStart = "  {";
                lanBrracesEnd  = "  }";
                break;

            case LanguageEnum.Java:
                //using for jAVA class
                lanClassDef    = "  public class";
                lanbracesStart = "  {";
                lanBrracesEnd  = "  }";
                break;
            }

            foreach (KeyValuePair <string, List <string> > codeClassItem in checkClassNamesDic)
            {
                switch (lan)
                {
                case LanguageEnum.CSharp:
                    //using for C# class
                    codeBuilder.AppendLine(cSharpUsings.ToString());

                    break;

                case LanguageEnum.PHP:
                    break;

                case LanguageEnum.Java:
                    //using for jAVA class
                    codeBuilder.AppendLine(javaUsings.ToString());
                    break;
                }

                switch (lan)
                {
                case LanguageEnum.CSharp:
                    //using for C# class
                    if (!string.IsNullOrEmpty(namespaceMapping))
                    {
                        codeBuilder.AppendLine("namespace " + namespaceMapping + "\n{");
                    }

                    break;

                case LanguageEnum.PHP:
                    break;

                case LanguageEnum.Java:
                    if (!string.IsNullOrEmpty(namespaceMapping))
                    {
                        codeBuilder.AppendLine("package " + namespaceMapping + ";");
                    }
                    break;
                }

                switch (prop)
                {
                case LanAttributes.None:
                    break;

                case LanAttributes.DataContract:
                    codeBuilder.AppendLine("  [DataContract]");
                    break;

                case LanAttributes.Json:
                    break;
                }
                codeBuilder.AppendLine(lanClassDef + " " + codeClassItem.Key);
                codeBuilder.AppendLine(lanbracesStart);
                codeClassItem.Value.ForEach(delegate(string props)
                {
                    codeBuilder.AppendLine("  " + props);
                });
                codeBuilder.AppendLine(lanBrracesEnd);

                switch (lan)
                {
                case LanguageEnum.CSharp:
                    //using for C# class
                    if (!string.IsNullOrEmpty(namespaceMapping))
                    {
                        codeBuilder.AppendLine("\n}");
                    }

                    break;
                }

                var sanitizer = new HtmlSanitizer();
                var sanitized = sanitizer.Sanitize(codeBuilder.ToString());
                codeList.Add(sanitized);

                //we need the class to get it from angularjs in the filter and represent it in the accordian

                codeBuilder.Length   = 0;
                codeBuilder.Capacity = 0;

                if (extractfiles)
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    using (TextWriter writer = File.CreateText(path + @"\" + codeClassItem.Key))
                    {
                        writer.Write(codeBuilder);

                        codeBuilder.Length = 0;
                    }
                }
            }

            return(codeList);
        }
示例#39
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);
        }
示例#40
0
        public void TestForStyleTagWithEmptyValue()
        {
            const string html = "<html><head></head><body><style><!-- #some-id div.SomeSection {} --></style><div id=\"some-id\"><div class=\"SomeSection\">text</div></div></body></html>";

            HtmlSanitizer.Sanitize(html, false);
        }
示例#41
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);
        }
示例#42
0
 public AppsHelper(ApplicationDbContextFactory contextFactory, CurrencyNameTable currencies, RateFetcher rateFetcher, HtmlSanitizer htmlSanitizer)
 {
     _ContextFactory = contextFactory;
     _Currencies     = currencies;
     _RateFetcher    = rateFetcher;
     _HtmlSanitizer  = htmlSanitizer;
 }
示例#43
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);
        }
示例#44
0
 /// <summary>
 /// Configure the renderer and sanitizer
 /// </summary>
 public MarkdownRenderer()
 {
     LoaderContext.RegisterSingletonInstance(this);
     m_mdpipeline = new MarkdownPipelineBuilder().Build();
     m_sanitizer  = new HtmlSanitizer();
 }
示例#45
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);
        }
示例#46
0
 public void Sanitize(HtmlSanitizer sanitizer)
 {
     Email = sanitizer.Sanitize(Email);
 }
示例#47
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);
        }
示例#48
0
        public ScrapedObj GetUrls(ScrapeRequest model)
        {
            // ScrapingBrowser Browser = new ScrapingBrowser();
            // Browser.AllowAutoRedirect = true; // Browser has settings you can access in setup
            // Browser.AllowMetaRedirect = true;

            // WebPage PageResult = Browser.NavigateToPage(new Uri(model.Website));



            // ScrapeRequest model
            var webClient  = new WebClient();
            var htmlString = webClient.DownloadString(model.Website);

            //sanitize the downloaded html String
            var    sanitizer       = new HtmlSanitizer();
            string sanitizedString = sanitizer.Sanitize(htmlString, model.Website, null);


            var htmlDocument = new HtmlDocument();

            htmlDocument.LoadHtml(sanitizedString);
            var htmlBody = htmlDocument.DocumentNode.SelectSingleNode("//body");

            string        rx2      = @"[^.?!]*(?<=[.?\s!])" + model.SearchingFor + @"(?=[\s.?!])[^.?!]*[.?!]";
            List <string> matches3 = new List <string>();
            List <string> matches4 = new List <string>();

            try{
                foreach (Match match3 in Regex.Matches(htmlBody.InnerText, rx2, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(5)))
                {
                    matches3.Add(Regex.Replace(match3.Value, @"[^\w\s\.?,!@-]", "",
                                               RegexOptions.None, TimeSpan.FromSeconds(.5)));
                }
                foreach (Match match4 in Regex.Matches(htmlBody.InnerHtml, rx2, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(5)))
                {
                    //matches4.Add(match4.Value);
                    matches4.Add(Regex.Replace(match4.Value, @"[^\w\s\.?,!@-]", "",
                                               RegexOptions.None, TimeSpan.FromSeconds(.5)));
                }
            }
            catch (RegexMatchTimeoutException) {
            }
            ScrapedObj sO = new ScrapedObj();

            sO.ScrappedThing = matches3;

            //dumbHrefs
            List <string> listOfHrefs = new List <string>();
            //
            //Match m;
            string HRefPattern = "href\\s*=\\s*(?:[\"'](?<1>[^\"']*)[\"']|(?<1>\\S+))";

            try
            {
                foreach (Match href in Regex.Matches(htmlBody.InnerHtml, HRefPattern,
                                                     RegexOptions.IgnoreCase | RegexOptions.Compiled,
                                                     TimeSpan.FromSeconds(1)))
                {
                    listOfHrefs.Add(href.Value);
                }
            }
            catch (RegexMatchTimeoutException) {
            }
            Console.Beep();


            // SpeechSynthesizer synth = new SpeechSynthesizer();

            // // Configure the audio output.
            // synth.SetOutputToDefaultAudioDevice();

            // // Speak a string.
            // synth.Speak("This example demonstrates a basic use of Speech Synthesizer");

            // Install-Package ScrapySharp using ScrapySharp.Network; using HtmlAgilityPack; using ScrapySharp.Extensions
            // dotnet add package ScrapySharp --version 3.0.0

            Console.Beep(659, 125); Console.Beep(659, 125); Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(167); Console.Beep(523, 125); Console.Beep(659, 125); Thread.Sleep(125); Console.Beep(784, 125); Thread.Sleep(375); Console.Beep(392, 125); Thread.Sleep(375); Console.Beep(523, 125); Thread.Sleep(250); Console.Beep(392, 125); Thread.Sleep(250); Console.Beep(330, 125); Thread.Sleep(250); Console.Beep(440, 125); Thread.Sleep(125); Console.Beep(494, 125); Thread.Sleep(125); Console.Beep(466, 125); Thread.Sleep(42); Console.Beep(440, 125); Thread.Sleep(125); Console.Beep(392, 125); Thread.Sleep(125); Console.Beep(659, 125);
            Thread.Sleep(125); Console.Beep(784, 125); Thread.Sleep(125); Console.Beep(880, 125); Thread.Sleep(125); Console.Beep(698, 125); Console.Beep(784, 125); Thread.Sleep(125); Console.Beep(659, 125);
            Thread.Sleep(125); Console.Beep(523, 125); Thread.Sleep(125); Console.Beep(587, 125); Console.Beep(494, 125); Thread.Sleep(125); Console.Beep(523, 125); Thread.Sleep(250); Console.Beep(392, 125); Thread.Sleep(250); Console.Beep(330, 125); Thread.Sleep(250); Console.Beep(440, 125); Thread.Sleep(125); Console.Beep(494, 125); Thread.Sleep(125); Console.Beep(466, 125); Thread.Sleep(42); Console.Beep(440, 125); Thread.Sleep(125); Console.Beep(392, 125); Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(125); Console.Beep(784, 125); Thread.Sleep(125); Console.Beep(880, 125); Thread.Sleep(125); Console.Beep(698, 125); Console.Beep(784, 125);
            Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(125); Console.Beep(523, 125); Thread.Sleep(125); Console.Beep(587, 125); Console.Beep(494, 125); Thread.Sleep(375); Console.Beep(784, 125); Console.Beep(740, 125); Console.Beep(698, 125);
            Thread.Sleep(42); Console.Beep(622, 125); Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(167); Console.Beep(415, 125); Console.Beep(440, 125); Console.Beep(523, 125); Thread.Sleep(125); Console.Beep(440, 125); Console.Beep(523, 125); Console.Beep(587, 125); Thread.Sleep(250); Console.Beep(784, 125); Console.Beep(740, 125); Console.Beep(698, 125); Thread.Sleep(42); Console.Beep(622, 125); Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(167); Console.Beep(698, 125); Thread.Sleep(125); Console.Beep(698, 125); Console.Beep(698, 125);
            Thread.Sleep(625); Console.Beep(784, 125); Console.Beep(740, 125); Console.Beep(698, 125); Thread.Sleep(42); Console.Beep(622, 125); Thread.Sleep(125); Console.Beep(659, 125);
            Thread.Sleep(167); Console.Beep(415, 125); Console.Beep(440, 125); Console.Beep(523, 125); Thread.Sleep(125); Console.Beep(440, 125); Console.Beep(523, 125); Console.Beep(587, 125); Thread.Sleep(250); Console.Beep(622, 125); Thread.Sleep(250); Console.Beep(587, 125); Thread.Sleep(250); Console.Beep(523, 125); Thread.Sleep(1125); Console.Beep(784, 125); Console.Beep(740, 125); Console.Beep(698, 125); Thread.Sleep(42); Console.Beep(622, 125); Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(167); Console.Beep(415, 125); Console.Beep(440, 125); Console.Beep(523, 125);
            Thread.Sleep(125); Console.Beep(440, 125); Console.Beep(523, 125); Console.Beep(587, 125); Thread.Sleep(250); Console.Beep(784, 125); Console.Beep(740, 125); Console.Beep(698, 125); Thread.Sleep(42); Console.Beep(622, 125); Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(167); Console.Beep(698, 125);
            Thread.Sleep(125); Console.Beep(698, 125); Console.Beep(698, 125); Thread.Sleep(625); Console.Beep(784, 125); Console.Beep(740, 125); Console.Beep(698, 125); Thread.Sleep(42); Console.Beep(622, 125); Thread.Sleep(125); Console.Beep(659, 125); Thread.Sleep(167); Console.Beep(415, 125); Console.Beep(440, 125); Console.Beep(523, 125); Thread.Sleep(125); Console.Beep(440, 125); Console.Beep(523, 125); Console.Beep(587, 125); Thread.Sleep(250); Console.Beep(622, 125); Thread.Sleep(250); Console.Beep(587, 125); Thread.Sleep(250); Console.Beep(523, 125);

            return(sO);
        }
示例#49
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);
        }
示例#50
0
        private string SanitizeMessage(string message)
        {
            var sanitizer = new HtmlSanitizer();

            return(sanitizer.Sanitize(message));
        }
示例#51
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);
        }
 public HtmlService()
 {
     this.htmlSanitizer = new HtmlSanitizer();
     this.htmlSanitizer.AllowedAttributes.Add("class");
 }
示例#53
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);
        }
示例#54
0
        protected void AppendMessage(bool incoming, Message msg)
        {
            string iconPath = null;
            string from     = null;
            JID    fromJid  = null;

            if (msg.From == null)
            {
                from    = m_Account.UserDisplayName;
                fromJid = m_Account.Jid;
            }
            else
            {
                if (this is MucHandler)
                {
                    // FIXME: Abstract this...
                    var participant = ((MucHandler)this).Room.Participants[msg.From];
                    if (participant != null)
                    {
                        fromJid = (!String.IsNullOrEmpty(participant.RealJID)) ? participant.RealJID : participant.NickJID;
                        from    = participant.Nick;
                    }
                    else
                    {
                        fromJid = msg.From;
                        from    = msg.From.Resource;
                    }
                }
                else if (this is ChatHandler && ((ChatHandler)this).IsMucMessage)
                {
                    fromJid = msg.From;
                    from    = msg.From.Resource;
                }
                else
                {
                    fromJid = msg.From;
                    from    = m_Account.GetDisplayName(msg.From);
                }
            }

            foreach (XmlNode child in msg)
            {
                if (child.NamespaceURI == Namespace.ChatStates)
                {
                    TypingState state = TypingState.None;
                    if (child.LocalName == "active")
                    {
                        state = TypingState.Active;
                    }
                    else if (child.LocalName == "composing")
                    {
                        state = TypingState.Composing;
                    }
                    else if (child.LocalName == "paused")
                    {
                        state = TypingState.Paused;
                    }
                    else if (child.LocalName == "inactive")
                    {
                        state = TypingState.Inactive;
                    }
                    else if (child.LocalName == "gone")
                    {
                        state = TypingState.Gone;
                    }
                    else
                    {
                        Console.WriteLine(String.Format("Unknown chatstate from {0}: {1}", from, child.LocalName));
                    }

                    var typingContent = new ChatContentTyping(m_Account, fromJid, from, null, state);
                    OnNewContent(typingContent);
                }
            }

            if (msg.Body != null || msg.Html != null)
            {
                string body = null;

                if (!String.IsNullOrEmpty(msg.Html))
                {
                    body = HtmlSanitizer.Sanitize(msg.Html, true);
                }
                else
                {
                    body = Util.EscapeHtml(msg.Body);
                    body = Util.Linkify(body);
                    body = body.Replace("  ", " &nbsp;");
                    body = body.Replace("\t", " &nbsp;&nbsp;&nbsp;");
                    body = body.Replace("\r\n", "<br/>");
                    body = body.Replace("\n", "<br/>");
                }

                var guiService = ServiceManager.Get <GuiService>();
                foreach (var formatter in guiService.MessageDisplayFormatters)
                {
                    if (formatter.SupportsMessage(body, msg))
                    {
                        body = formatter.FormatMessage(body, msg);
                        if (formatter.StopAfter)
                        {
                            break;
                        }
                    }
                }

                DateTime date = DateTime.Now;

                var nsmgr = new XmlNamespaceManager(msg.OwnerDocument.NameTable);
                nsmgr.AddNamespace("delay", "jabber:x:delay");
                var delay = (XmlElement)msg.SelectSingleNode("delay:x", nsmgr);
                if (delay != null)
                {
                    string stamp = delay.GetAttribute("stamp");
                    // CCYYMMDDThh:mm:ss
                    date = DateTime.ParseExact(stamp, @"yyyyMMdd\THH:mm:ss", null).ToLocalTime();
                }

                var content = new ChatContentMessage(m_Account, fromJid, from, msg.To, date);
                content.IsOutgoing  = !incoming;
                content.MessageHtml = body;

                OnNewContent(content);
            }
        }
示例#55
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);
        }
示例#56
0
 public BugInputModel()
 {
     this.sanitizer = new HtmlSanitizer();
 }
示例#57
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);
        }
示例#58
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);
 }
示例#59
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);
        }
示例#60
0
 public TwitchChatNotificationHandler(INotifierMediatorService notifierMediatorService, IMapper mapper, IOptions <TwitchConfig> config, HtmlSanitizer sanitizer, TwitchAPI twitchApiClient, IHubContext <TwitchHub> twitchHub)
 {
     _notifierMediatorService = notifierMediatorService;
     _mapper          = mapper;
     _sanitizer       = sanitizer;
     _twitchApiClient = twitchApiClient;
     _twitchHub       = twitchHub;
     _config          = config.Value;
 }