Beispiel #1
0
        protected override void VisitTextPart(TextPart entity)
        {
            string text;

            if (entity.IsHtml)
            {
                var converter = new HtmlToHtml {
                    HtmlTagCallback = HtmlTagCallback
                };

                text = converter.Convert(entity.Text);
            }
            else if (entity.IsFlowed)
            {
                var converter = new FlowedToText();

                text = converter.Convert(entity.Text);
                text = QuoteText(text);
            }
            else
            {
                // quote the original message text
                text = QuoteText(entity.Text);
            }

            var part = new TextPart(entity.ContentType.MediaSubtype.ToLowerInvariant())
            {
                Text = text
            };

            Push(part);
        }
Beispiel #2
0
        // Token: 0x060018CE RID: 6350 RVA: 0x00055CC0 File Offset: 0x00053EC0
        protected static string ConvertToSafeHtml(string html)
        {
            string text = null;

            if (html != null)
            {
                HtmlToHtml htmlToHtml = new HtmlToHtml();
                htmlToHtml.FilterHtml         = true;
                htmlToHtml.OutputHtmlFragment = true;
                using (TextReader textReader = new StringReader(html))
                {
                    using (TextWriter textWriter = new StringWriter())
                    {
                        try
                        {
                            htmlToHtml.Convert(textReader, textWriter);
                            text = textWriter.ToString().Trim();
                            if (text.StartsWith("<div>", StringComparison.OrdinalIgnoreCase))
                            {
                                text = text.Substring("<div>".Length, text.Length - "<div>".Length - "</div>".Length);
                            }
                        }
                        catch (ExchangeDataException localizedException)
                        {
                            GetLinkPreview.ThrowLocalizedException("HtmlConversionFailed", localizedException);
                        }
                    }
                }
            }
            return(text);
        }
Beispiel #3
0
        // Token: 0x06001B94 RID: 7060 RVA: 0x00069C84 File Offset: 0x00067E84
        public static string CleanHtml(string input)
        {
            string     text       = null;
            HtmlToHtml htmlToHtml = new HtmlToHtml();

            htmlToHtml.FilterHtml         = true;
            htmlToHtml.OutputHtmlFragment = true;
            string result;

            using (TextReader textReader = new StringReader(input))
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    try
                    {
                        htmlToHtml.Convert(textReader, textWriter);
                        text = textWriter.ToString();
                    }
                    catch (ExchangeDataException innerException)
                    {
                        throw FaultExceptionUtilities.CreateFault(new OwaCannotSanitizeHtmlException("Sanitization of the HTML failed", innerException, htmlToHtml), FaultParty.Sender);
                    }
                    result = text;
                }
            }
            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// Sanitizes input HTML fragment for safe display on browser.
        /// </summary>
        /// <param name="input">Malicious HTML fragment</param>
        /// <returns>Safe HTML fragment</returns>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static string GetSafeHtmlFragment(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            using TextReader stringReader = new StringReader(input);
            using TextWriter stringWriter = new StringWriter();
            HtmlToHtml htmlObject = new HtmlToHtml
            {
                FilterHtml         = true,
                OutputHtmlFragment = true,
                NormalizeHtml      = true
            };

            htmlObject.Convert(stringReader, stringWriter);

            if (stringWriter.ToString().Length == 0)
            {
                return(string.Empty);
            }

            // stripping <div> tags
            string output = stringWriter.ToString();

            if (string.Equals(output.Substring(0, 5), "<div>", System.StringComparison.OrdinalIgnoreCase))
            {
                output = output.Substring(5);
                output = output.Substring(0, output.Length - 8);
            }

            return(output);
        }
        public static string MakeSafeHtml(int traceId, string unsafeHtml)
        {
            MailTipsUtility.GetMailTipsTracer.TraceDebug((long)traceId, "Entering MakeSafeHtml");
            HtmlToHtml htmlToHtml = new HtmlToHtml();

            htmlToHtml.FilterHtml         = true;
            htmlToHtml.OutputHtmlFragment = true;
            string result;

            using (TextReader textReader = new StringReader(unsafeHtml))
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    try
                    {
                        htmlToHtml.Convert(textReader, textWriter);
                    }
                    catch (ExchangeDataException ex)
                    {
                        MailTipsUtility.GetMailTipsTracer.TraceDebug <string>((long)traceId, "Exception thrown while filtering HTML: {0}", ex.Message);
                        return(string.Empty);
                    }
                    result = textWriter.ToString().Trim();
                }
            }
            return(result);
        }
Beispiel #6
0
        /// <summary>
        /// Returns a safe version of HTML fragment by either sanitizing or removing all malicious scripts.
        /// </summary>
        /// <param name="input">String containing user supplied HTML</param>
        /// <returns>Safe version of user supplied HTML</returns>
        /// <remarks>Input string is passed through the HtmlToHtml class where any unsafe HTML
        /// it might contain is stripped out. A white list of non scriptable tags and attributes
        /// are used to parse the input HTML fragment for malicious scripts. For santizing entire
        /// HTML pages see <see cref="GetSafeHtml(string)"/>.
        /// </remarks>
        public static string GetSafeHtmlFragment(string input)
        {
            // Check for NULL || EMPTY
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            TextReader stringReader = null;
            TextWriter stringWriter = null;
            HtmlToHtml htmlObject   = null;

            try
            {
                htmlObject   = new HtmlToHtml();
                stringReader = new StringReader(input);
                stringWriter = new StringWriter(CultureInfo.InvariantCulture);

                // Set the properties.
                htmlObject.FilterHtml         = true;
                htmlObject.OutputHtmlFragment = true;
                htmlObject.NormalizeHtml      = true;

                htmlObject.Convert(stringReader, stringWriter);

                if (stringWriter.ToString().Length != 0)
                {
                    //stripping <div> tags
                    var output = stringWriter.ToString();
                    if (output.Substring(0, 5).ToLower() == "<div>")
                    {
                        //strpping begin tag
                        output = output.Substring(5);

                        //stripping end tag + linefeed
                        output = output.Substring(0, output.Length - 8);
                    }
                    return(output);
                }
                else
                {
                    return(string.Empty);
                }
            }
            finally
            {
                if (stringReader != null)
                {
                    stringReader.Close();
                }

                if (stringWriter != null)
                {
                    stringWriter.Close();
                }
            }
        }
Beispiel #7
0
        public void TestArgumentExceptions()
        {
            var converter = new HtmlToHtml();
            var reader    = new StringReader("");
            var writer    = new StringWriter();

            Assert.AreEqual(TextFormat.Html, converter.InputFormat);
            Assert.AreEqual(TextFormat.Html, converter.OutputFormat);
            Assert.IsFalse(converter.DetectEncodingFromByteOrderMark);
            Assert.IsFalse(converter.FilterComments);
            Assert.IsFalse(converter.FilterHtml);
            Assert.IsNull(converter.Footer);
            Assert.IsNull(converter.Header);
            Assert.AreEqual(HeaderFooterFormat.Text, converter.FooterFormat);
            Assert.AreEqual(HeaderFooterFormat.Text, converter.HeaderFormat);

            Assert.Throws <ArgumentNullException> (() => converter.Convert((TextReader)null, writer));
            Assert.Throws <ArgumentNullException> (() => converter.Convert(reader, (TextWriter)null));
        }
Beispiel #8
0
        /// <summary>
        /// Get safe version of HTML fragment.
        /// </summary>
        /// <param name="sourceReader"> TextReader as source of HTML</param>
        /// <param name="destinationStream">Stream as safeHTML</param>
        public static void GetSafeHtmlFragment(TextReader sourceReader, Stream destinationStream)
        {
            var htmlObject = new HtmlToHtml();

            // Set the properties.
            htmlObject.FilterHtml         = true;
            htmlObject.OutputHtmlFragment = true;
            htmlObject.NormalizeHtml      = true;

            htmlObject.Convert(sourceReader, destinationStream);
        }
Beispiel #9
0
        /// <summary>
        /// Sanitizes input HTML document for safe display on browser.
        /// </summary>
        /// <param name="sourceReader">Source text reader with malicious HTML</param>
        /// <param name="destinationWriter">Text Writer to write safe HTML</param>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static void GetSafeHtml(TextReader sourceReader, TextWriter destinationWriter)
        {
            HtmlToHtml htmlObject = new HtmlToHtml
            {
                FilterHtml         = true,
                OutputHtmlFragment = false,
                NormalizeHtml      = true
            };

            htmlObject.Convert(sourceReader, destinationWriter);
        }
Beispiel #10
0
        /// <summary>
        /// Get safe version of HTML fragment.
        /// </summary>
        /// <param name="sourceReader"> TextReader as source of HTML</param>
        /// <param name="destinationWriter">TextWriter as safeHTML</param>
        public static void GetSafeHtmlFragment(TextReader sourceReader, TextWriter destinationWriter)
        {
            HtmlToHtml htmlObject = htmlObject = new HtmlToHtml();

            // Set the properties.
            htmlObject.FilterHtml         = true;
            htmlObject.OutputHtmlFragment = true;
            htmlObject.NormalizeHtml      = true;

            htmlObject.Convert(sourceReader, destinationWriter);
        }
Beispiel #11
0
        /// <summary>
        /// Sanitizes input HTML fragment for safe display on browser.
        /// </summary>
        /// <param name="sourceReader">Source text reader with malicious HTML</param>
        /// <param name="destinationStream">Stream to write safe HTML</param>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static void GetSafeHtmlFragment(TextReader sourceReader, Stream destinationStream)
        {
            HtmlToHtml htmlObject = new HtmlToHtml
            {
                FilterHtml         = true,
                OutputHtmlFragment = true,
                NormalizeHtml      = true
            };

            htmlObject.Convert(sourceReader, destinationStream);
        }
        public void TestSimpleHtmlToHtml()
        {
            string expected  = File.ReadAllText("../../TestData/html/xamarin3.xhtml");
            string text      = File.ReadAllText("../../TestData/html/xamarin3.html");
            var    converter = new HtmlToHtml {
                HtmlTagCallback = ReplaceUrlsWithFileNames
            };
            var result = converter.Convert(text);

            Assert.AreEqual(expected, result);
        }
Beispiel #13
0
        public void TestFilterHtml()
        {
            const string input     = "<html><head><script>/* this is a script */</script></head><body>Here is the body content which seems fine so far</body></html>";
            const string expected  = "<html><head></head><body>Here is the body content which seems fine so far</body></html>";
            var          converter = new HtmlToHtml {
                FilterHtml = true
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Beispiel #14
0
        public void TestFilterComments()
        {
            const string input     = "<html><head><!-- this is a comment --></head><body>Here is the body content <!-- this is another comment -->which seems fine so far</body></html>";
            const string expected  = "<html><head></head><body>Here is the body content which seems fine so far</body></html>";
            var          converter = new HtmlToHtml {
                FilterComments = true
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Beispiel #15
0
        public void TestSupressInnerContent()
        {
            const string input     = "<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=iso-8859-2\"><meta name=Generator content=\"Microsoft Word 15 (filtered medium)\"><!--[if !mso]><style>v\\:* {behavior:url(#default#VML);}\r\no\\:* {behavior:url(#default#VML);}\r\nw\\:* {behavior:url(#default#VML);}\r\n.shape{behavior:url(#default#VML);}\r\n</style><![endif]--><style><!--\r\n/* Font Definitions */\r\n@font-face\r\n\t{font-family:\"Cambria Math\";\r\n\tpanose-1:2 4 5 3 5 4 6 3 2 4;}\r\n@font-face\r\n\t{font-family:Calibri;\r\n\tpanose-1:2 15 5 2 2 2 4 3 2 4;}\r\n@font-face\r\n\t{font-family:\"Segoe UI\";\r\n\tpanose-1:2 11 5 2 4 2 4 2 2 3;}\r\n@font-face\r\n\t{font-family:Verdana;\r\n\tpanose-1:2 11 6 4 3 5 4 4 2 4;}\r\n/* Style Definitions */\r\np.MsoNormal, li.MsoNormal, div.MsoNormal\r\n\t{margin:0cm;\r\n\tmargin-bottom:.0001pt;\r\n\tfont-size:11.0pt;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tmso-fareast-language:EN-US;}\r\nh3\r\n\t{mso-style-priority:9;\r\n\tmso-style-link:\"Heading 3 Char\";\r\n\tmso-margin-top-alt:auto;\r\n\tmargin-right:0cm;\r\n\tmso-margin-bottom-alt:auto;\r\n\tmargin-left:0cm;\r\n\tfont-size:13.5pt;\r\n\tfont-family:\"Times New Roman\",serif;}\r\na:link, span.MsoHyperlink\r\n\t{mso-style-priority:99;\r\n\tcolor:#0563C1;\r\n\ttext-decoration:underline;}\r\na:visited,span.MsoHyperlinkFollowed\r\n\t{mso-style-priority:99;\r\n\tcolor:#954F72;\r\n\ttext-decoration:underline;}\r\nspan.Heading3Char\r\n\t{mso-style-name:\"Heading 3 Char\";\r\n\tmso-style-priority:9;\r\n\tmso-style-link:\"Heading 3\";\r\n\tfont-family:\"Times New Roman\",serif;\r\n\tmso-fareast-language:FR;\r\n\tfont-weight:bold;}\r\nspan.EmailStyle18\r\n\t{mso-style-type:personal;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tcolor:windowtext;}\r\nspan.EmailStyle19\r\n\t{mso-style-type:personal-reply;\r\n\tfont-family:\"Calibri\",sans-serif;\r\n\tcolor:#1F497D;}\r\n.MsoChpDefault\r\n\t{mso-style-type:export-only;\r\n\tfont-size:10.0pt;}\r\n@page WordSection1\r\n\t{size:612.0pt 792.0pt;\r\n\tmargin:70.85pt 70.85pt 70.85pt 70.85pt;}\r\ndiv.WordSection1\r\n\t{page:WordSection1;}\r\n--></style><!--[if gte mso 9]><xml>\r\n<o:shapedefaults v:ext=\"edit\" spidmax=\"1026\" />\r\n</xml><![endif]--><!--[if gte mso 9]><xml>\r\n<o:shapelayout v:ext=\"edit\">\r\n<o:idmap v:ext=\"edit\" data=\"1\" />\r\n</o:shapelayout></xml><![endif]--></head><body lang=FR link=\"#0563C1\" vlink=\"#954F72\">Here is the body content which seems fine so far</body></html>";
            const string expected  = "Here is the body content which seems fine so far";
            var          converter = new HtmlToHtml {
                HtmlTagCallback = SupressInnerContentCallback
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Beispiel #16
0
        public static void RenderMultipartRelated(MultipartRelated related, WebBrowserEditabil pWebBrowser)
        {
            var root      = related.Root;
            var multipart = root as Multipart;
            var text      = root as TextPart;

            if (multipart != null)
            {
                for (int i = multipart.Count; i > 0; i--)
                {
                    var body = multipart[i - 1] as TextPart;

                    if (body == null)
                    {
                        continue;
                    }

                    if (body.ContentType.IsMimeType("text", "html"))
                    {
                        text = body;
                        break;
                    }

                    if (text == null)
                    {
                        text = body;
                    }
                }
            }
            if (text != null)
            {
                if (text.ContentType.IsMimeType("text", "html"))
                {
                    var ctx       = new MultipartRelatedImageContext(related);
                    var converter = new HtmlToHtml()
                    {
                        HtmlTagCallback = ctx.HtmlTagCallback
                    };
                    var html = converter.Convert(text.Text);

                    pWebBrowser.DocumentText = html;
                }
                else
                {
                    RenderText(text, pWebBrowser);
                }
            }
            else
            {
                return;
            }
        }
Beispiel #17
0
        private void SetHtmlToBody(TextPart entity)
        {
            var converter = new HtmlToHtml
            {
                Header          = $"{UIStrings.MarkOfTheWeb}{Environment.NewLine}",
                HeaderFormat    = HeaderFooterFormat.Html,
                HtmlTagCallback = this.HtmlTagCallback
            };

            var html = entity.Text;

            if (!html.Contains("<head>") || !html.Contains("<body>"))
            {
                var beforeAfter = GetBeforeAfterFormatWrapper(UIStrings.HtmlToHtmlFormatWrapper);

                _body = converter.Convert(beforeAfter.Before + html + beforeAfter.After);
            }
            else
            {
                _body = converter.Convert(html);
            }
        }
Beispiel #18
0
        public void TestSimpleHtmlToHtml()
        {
            string expected  = File.ReadAllText(Path.Combine(TestHelper.ProjectDir, "TestData", "html", "xamarin3.xhtml"));
            string text      = File.ReadAllText(Path.Combine(TestHelper.ProjectDir, "TestData", "html", "xamarin3.html"));
            var    converter = new HtmlToHtml {
                Header = null, Footer = null, HtmlTagCallback = ReplaceUrlsWithFileNames
            };
            var result = converter.Convert(text);

            Assert.AreEqual(TextFormat.Html, converter.InputFormat, "InputFormat");
            Assert.AreEqual(TextFormat.Html, converter.OutputFormat, "OutputFormat");
            Assert.AreEqual(expected, result);
        }
Beispiel #19
0
        public void TestArgumentExceptions()
        {
            var converter = new HtmlToHtml();
            var reader    = new StringReader("");
            var writer    = new StringWriter();

            Assert.Throws <ArgumentNullException> (() => converter.InputEncoding  = null);
            Assert.Throws <ArgumentNullException> (() => converter.OutputEncoding = null);

            Assert.Throws <ArgumentOutOfRangeException> (() => converter.InputStreamBufferSize  = -1);
            Assert.Throws <ArgumentOutOfRangeException> (() => converter.OutputStreamBufferSize = -1);

            Assert.Throws <ArgumentNullException> (() => converter.Convert(null));
            Assert.Throws <ArgumentNullException> (() => converter.Convert((Stream)null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => converter.Convert(Stream.Null, (Stream)null));
            Assert.Throws <ArgumentNullException> (() => converter.Convert((TextReader)null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => converter.Convert(Stream.Null, (TextWriter)null));
            Assert.Throws <ArgumentNullException> (() => converter.Convert((TextReader)null, writer));
            Assert.Throws <ArgumentNullException> (() => converter.Convert(reader, (TextWriter)null));
            Assert.Throws <ArgumentNullException> (() => converter.Convert(new StreamReader(Stream.Null), (Stream)null));
            Assert.Throws <ArgumentNullException> (() => converter.Convert((Stream)null, new StreamWriter(Stream.Null)));
            Assert.Throws <ArgumentNullException> (() => converter.Convert(new StreamReader(Stream.Null), (TextWriter)null));
        }
Beispiel #20
0
        public void TestTextHeaderFooter()
        {
            const string input     = "<body>Here is the body content which seems fine so far</body>";
            const string expected  = "&lt;html&gt;&lt;head&gt;&lt;/head&gt;<br/><body>Here is the body content which seems fine so far</body>&lt;/html&gt;<br/>";
            var          converter = new HtmlToHtml {
                HeaderFormat = HeaderFooterFormat.Text,
                Header       = "<html><head></head>",
                FooterFormat = HeaderFooterFormat.Text,
                Footer       = "</html>"
            };

            var result = converter.Convert(input);

            Assert.AreEqual(expected, result);
        }
Beispiel #21
0
        public string RenderMultipartRelated(MultipartRelated related)
        {
            var root = related.Root;
            var text = root as TextPart;

            if (root is Multipart multipart)
            {
                for (int i = multipart.Count; i > 0; i--)
                {
                    if (!(multipart[i - 1] is TextPart body))
                    {
                        continue;
                    }

                    if (body.ContentType.IsMimeType("text", "html"))
                    {
                        text = body;
                        break;
                    }

                    if (text == null)
                    {
                        text = body;
                    }
                }
            }

            if (text != null)
            {
                if (text.ContentType.IsMimeType("text", "html"))
                {
                    var ctx       = new MultipartRelatedImageContext(related);
                    var converter = new HtmlToHtml()
                    {
                        HtmlTagCallback = ctx.HtmlTagCallback
                    };
                    return(converter.Convert(text.Text));
                }
                else
                {
                    return(RenderText(text));
                }
            }
            else
            {
                return("Uncknown message type.");
            }
        }
Beispiel #22
0
        /// <summary>
        /// Returns a safe version of HTML page by either sanitizing or removing all malicious scripts.
        /// </summary>
        /// <param name="input">String containing user supplied HTML</param>
        /// <returns>Safe version of user supplied HTML</returns>
        /// <remarks>Input string is passed through the HtmlToHtml class where any unsafe HTML
        /// it might contain is stripped out. A white list of non scriptable tags and attributes
        /// are used to parse the input HTML page for malicious scripts. For santizing simple
        /// HTML fragments see <see cref="GetSafeHtmlFragment(string)"/>.
        /// </remarks>

        public static string GetSafeHtml(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            TextReader stringReader = null;
            TextWriter stringWriter = null;
            HtmlToHtml htmlObject   = null;

            try
            {
                htmlObject   = new HtmlToHtml();
                stringReader = new StringReader(input);
                stringWriter = new StringWriter(CultureInfo.InvariantCulture);

                // Set the properties.
                htmlObject.FilterHtml         = true;
                htmlObject.OutputHtmlFragment = false;
                htmlObject.NormalizeHtml      = true;

                htmlObject.Convert(stringReader, stringWriter);

                if (stringWriter.ToString().Length != 0)
                {
                    return(stringWriter.ToString());
                }
                else
                {
                    return(string.Empty);
                }
            }
            finally
            {
                if (stringReader != null)
                {
                    stringReader.Close();
                }

                if (stringWriter != null)
                {
                    stringWriter.Close();
                }
            }
        }
        // Token: 0x0600003F RID: 63 RVA: 0x00004608 File Offset: 0x00002808
        private bool TryWriteNotificationWithAppendedComments(DsnHumanReadableWriter notificationWriter, MessageItem rejectItem, StreamAttachment commentAttachment, ApprovalInformation info)
        {
            bool     result             = true;
            string   htmlModerationBody = notificationWriter.GetHtmlModerationBody(info);
            Charset  textCharset        = commentAttachment.TextCharset;
            Encoding inputEncoding      = null;

            if (textCharset == null || !textCharset.TryGetEncoding(out inputEncoding))
            {
                return(false);
            }
            Charset charset = textCharset;

            if (!ModeratedDLApplication.IsEncodingMatch(info.Codepages, textCharset.CodePage))
            {
                charset = Charset.UTF8;
            }
            BodyWriteConfiguration configuration = new BodyWriteConfiguration(BodyFormat.TextHtml, charset.Name);

            using (Stream stream = rejectItem.Body.OpenWriteStream(configuration))
            {
                HtmlToHtml htmlToHtml = new HtmlToHtml();
                htmlToHtml.Header             = htmlModerationBody;
                htmlToHtml.HeaderFooterFormat = HeaderFooterFormat.Html;
                htmlToHtml.InputEncoding      = inputEncoding;
                htmlToHtml.OutputEncoding     = charset.GetEncoding();
                try
                {
                    using (Stream contentStream = commentAttachment.GetContentStream(PropertyOpenMode.ReadOnly))
                    {
                        htmlToHtml.Convert(contentStream, stream);
                        stream.Flush();
                    }
                }
                catch (ExchangeDataException arg)
                {
                    ModeratedDLApplication.diag.TraceDebug <ExchangeDataException>(0L, "Attaching comments failed with {0}", arg);
                    result = false;
                }
            }
            return(result);
        }
Beispiel #24
0
        /// <summary>
        /// Sanitizes input HTML document for safe display on browser.
        /// </summary>
        /// <param name="input">Malicious HTML Document</param>
        /// <returns>A santizied HTML document</returns>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static string GetSafeHtml(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            using TextReader stringReader = new StringReader(input);
            using TextWriter stringWriter = new StringWriter();
            HtmlToHtml htmlObject = new HtmlToHtml
            {
                FilterHtml         = true,
                OutputHtmlFragment = false,
                NormalizeHtml      = true
            };

            htmlObject.Convert(stringReader, stringWriter);

            return(stringWriter.ToString().Length != 0 ? stringWriter.ToString() : string.Empty);
        }
Beispiel #25
0
        public static string SanitizeHtml(string unsafeHtml)
        {
            if (string.IsNullOrEmpty(unsafeHtml))
            {
                return(unsafeHtml);
            }
            string result;

            using (StringReader stringReader = new StringReader(unsafeHtml))
            {
                using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
                {
                    HtmlToHtml htmlToHtml = new HtmlToHtml();
                    TextConvertersInternalHelpers.SetPreserveDisplayNoneStyle(htmlToHtml, true);
                    htmlToHtml.InputEncoding  = Encoding.UTF8;
                    htmlToHtml.OutputEncoding = Encoding.UTF8;
                    htmlToHtml.FilterHtml     = true;
                    htmlToHtml.Convert(stringReader, stringWriter);
                    result = stringWriter.ToString();
                }
            }
            return(result);
        }
Beispiel #26
0
    protected override void VisitTextPart(TextPart entity)
    {
        TextConverter converter;

        if (foundBody)
        {
            // since we've already found the body, treat this as an
            // attachment
            attachments.Add(entity);
            return;
        }

        if (entity.IsHtml)
        {
            converter = new HtmlToHtml {
                HtmlTagCallback = HtmlTagCallback
            };

            converter.Convert(entity.Text);
        }

        foundBody = true;
    }
        /// <summary>
        /// Sanitizes input HTML fragment for safe display on browser.
        /// </summary>
        /// <param name="input">Malicious HTML fragment</param>
        /// <returns>Safe HTML fragment</returns>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static string GetSafeHtmlFragment(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }
            string result;

            using (TextReader textReader = new StringReader(input))
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    HtmlToHtml htmlToHtml = new HtmlToHtml
                    {
                        FilterHtml         = true,
                        OutputHtmlFragment = true,
                        NormalizeHtml      = true
                    };
                    htmlToHtml.Convert(textReader, textWriter);
                    if (textWriter.ToString().Length == 0)
                    {
                        result = string.Empty;
                    }
                    else
                    {
                        string text = textWriter.ToString();
                        if (text.Substring(0, 5).ToLower() == "<div>")
                        {
                            text = text.Substring(5);
                            text = text.Substring(0, text.Length - 8);
                        }
                        result = text;
                    }
                }
            }
            return(result);
        }
Beispiel #28
0
        /// <summary>
        /// Sanitizes input HTML fragment for safe display on browser.
        /// </summary>
        /// <param name="input">Malicious HTML fragment</param>
        /// <returns>Safe HTML fragment</returns>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static string GetSafeHtmlFragment(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            using (TextReader stringReader = new StringReader(input))
            {
                using (TextWriter stringWriter = new StringWriter())
                {
                    HtmlToHtml htmlObject = new HtmlToHtml
                    {
                        FilterHtml         = true,
                        OutputHtmlFragment = true,
                        NormalizeHtml      = true
                    };

                    htmlObject.Convert(stringReader, stringWriter);

                    if (stringWriter.ToString().Length == 0)
                    {
                        return(string.Empty);
                    }

                    // stripping <div> tags
                    string output = stringWriter.ToString();
                    if (output.Substring(0, 5).ToLower() == "<div>")
                    {
                        output = output.Substring(5);
                        output = output.Substring(0, output.Length - 8);
                    }

                    return(output);
                }
            }
        }
Beispiel #29
0
 // Token: 0x060003E0 RID: 992 RVA: 0x0000E8BC File Offset: 0x0000CABC
 private static void SanitizeMailTips(ADRecipient recipient)
 {
     if (recipient.MailTipTranslations != null)
     {
         bool isReadOnly = recipient.IsReadOnly;
         if (isReadOnly)
         {
             recipient.SetIsReadOnly(false);
         }
         for (int i = 0; i < recipient.MailTipTranslations.Count; i++)
         {
             string str;
             string text;
             if (ADRecipient.TryGetMailTipParts(recipient.MailTipTranslations[i], out str, out text) && !string.IsNullOrEmpty(text))
             {
                 using (StringReader stringReader = new StringReader(text))
                 {
                     using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
                     {
                         HtmlToHtml htmlToHtml = new HtmlToHtml();
                         htmlToHtml.SetPreserveDisplayNoneStyle(true);
                         htmlToHtml.InputEncoding  = Encoding.UTF8;
                         htmlToHtml.OutputEncoding = Encoding.UTF8;
                         htmlToHtml.FilterHtml     = true;
                         htmlToHtml.Convert(stringReader, stringWriter);
                         string str2 = stringWriter.ToString();
                         recipient.MailTipTranslations[i] = str + ":" + str2;
                     }
                 }
             }
         }
         if (isReadOnly)
         {
             recipient.SetIsReadOnly(true);
         }
     }
 }
        /// <summary>
        /// Sanitizes input HTML document for safe display on browser.
        /// </summary>
        /// <param name="input">Malicious HTML Document</param>
        /// <returns>A santizied HTML document</returns>
        /// <remarks>
        /// The method transforms and filters HTML of executable scripts.
        /// A safe list of tags and attributes are used to strip dangerous
        /// scripts from the HTML. HTML is also normalized where tags are
        /// properly closed and attributes are properly formatted.
        /// </remarks>
        public static string GetSafeHtml(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }
            string result;

            using (TextReader textReader = new StringReader(input))
            {
                using (TextWriter textWriter = new StringWriter())
                {
                    HtmlToHtml htmlToHtml = new HtmlToHtml
                    {
                        FilterHtml         = true,
                        OutputHtmlFragment = false,
                        NormalizeHtml      = true
                    };
                    htmlToHtml.Convert(textReader, textWriter);
                    result = ((textWriter.ToString().Length != 0) ? textWriter.ToString() : string.Empty);
                }
            }
            return(result);
        }