示例#1
0
def fixHtml(html):
    p = HTMLParser()
    return ''.join(
        [token.toxml() for token in p.parseFragment(html).childNodes])
示例#2
0
 def normalize_html(stream):
     p = HTMLParser(tokenizer=HTMLSanitizer)
     return ''.join([token.toxml() for token in p.parseFragment(stream).childNodes])
示例#3
0
class HTMLValidator:
  htmltags = [
    "a", "abbr", "acronym", "address", "applet", "area", "article", "aside",
    "audio", "b", "base", "basefont", "bdi", "bdo", "big", "blockquote", "body",
    "br", "button", "canvas", "caption", "center", "cite", "code", "col",
    "colgroup", "command", "data", "datagrid", "datalist", "dd", "del", "details", "dfn",
    "dialog", "dir", "div", "dl", "dt", "em", "eventsource",
    "fieldset", "figcaption", "figure", "font", "footer", "form", "frame",
    "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr",
    "html", "i", "iframe", "img", "input", "ins", "isindex", "kbd", "label",
    "legend", "li", "link", "m", "main", "mark", "map", "menu", "meta", "meter", "nav",
    "noframes", "noscript", "object", "ol", "optgroup", "option", "output",
    "p", "param", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section",
    "select", "slot", "small", "source", "span", "strike", "strong", "style", "sub", "summary",
    "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time",
    "title", "tr", "track", "tt", "u", "ul", "var", "xmp", "plaintext", "embed",
    "comment", "listing", "video", "wbr"]

  acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article',
    'aside', 'audio', 'b', 'bdi', 'big', 'blockquote', 'br', 'button', 'canvas',
    'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command',
    'data', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir',
    'div', 'dl', 'dt', 'em', 'eventsource', 'fieldset', "figcaption", 'figure',
    'footer', 'font', 'form', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
    'hgroup', 'hr', 'i', 'img', 'input', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li',
    'm', 'main', 'map', 'mark', 'menu', 'meter', 'multicol', 'nav', 'nextid', 'ol', 'output',
    'optgroup', 'option', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section',
    'select', 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong',
    'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'time', 'tfoot', 'th',
    'thead', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'noscript', 'wbr']

  acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
    'action', 'align', 'allow', 'allowfullscreen', 'allowpaymentrequest', 'alt', 'as', 'autoplay', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'axis',
    'background', 'balance', 'bgcolor', 'bgproperties', 'border',
    'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
    'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
    'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols',
    'colspan', 'compact', 'contenteditable', 'coords', 'crossorigin', 'data', 'datafld',
    'datapagesize', 'datasrc', 'datetime', 'decoding', 'default', 'delay', 'dir', 'dirname',
    'disabled', 'download', 'draggable', 'dynsrc', 'enctype','end', 'enterkeyhint', 'face', 'for',
    'form', 'formenctype',  'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus',
    'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode',
    'is', 'ismap', 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype', 'kind','keytype', 'label', 'lang', 'leftspacing', 'loading', 'list', 'longdesc',
    'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max',
    'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nohref', 'nonce',
    'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'playsinline', 'point-size', 'poster', 'preload',
    'prompt', 'pqg', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'repeat-max',
    'repeat-min', 'replace', 'required', 'rev', 'reversed', 'rightspacing', 'rows',
    'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'spellcheck', 'src',
    'srclang', 'srcset',
    'start', 'step', 'summary', 'suppress', 'tabindex', 'target', 'template',
    'title', 'toppadding', 'translate', 'type', 'unselectable', 'usemap', 'urn', 'valign',
    'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap',
    'xml:lang', 'xmlns']

  acceptable_css_properties = ['azimuth', 'background', 'background-color',
    'border', 'border-bottom', 'border-bottom-color', 'border-bottom-style',
    'border-bottom-width', 'border-collapse', 'border-color', 'border-left',
    'border-left-color', 'border-left-style', 'border-left-width',
    'border-right', 'border-right-color', 'border-right-style',
    'border-right-width', 'border-spacing', 'border-style', 'border-top',
    'border-top-color', 'border-top-style', 'border-top-width', 'border-width',
    'clear', 'color', 'cursor', 'direction', 'display', 'elevation', 'float',
    'font', 'font-family', 'font-size', 'font-style', 'font-variant',
    'font-weight', 'height', 'letter-spacing', 'line-height',
    'list-style-type', 'margin', 'margin-bottom', 'margin-left',
    'margin-right', 'margin-top', 'overflow', 'padding', 'padding-bottom',
    'padding-left', 'padding-right', 'padding-top', 'pause', 'pause-after',
    'pause-before', 'pitch', 'pitch-range', 'richness', 'speak',
    'speak-header', 'speak-numeral', 'speak-punctuation', 'speech-rate',
    'stress', 'text-align', 'text-decoration', 'text-indent', 'unicode-bidi',
    'vertical-align', 'voice-family', 'volume', 'white-space', 'width']

  # survey of common keywords found in feeds
  acceptable_css_keywords = ['aqua', 'auto', 'black', 'block', 'blue', 'bold',
    'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', 'dotted',
    'fuchsia', 'gray', 'green', '!important', 'italic', 'left', 'lime',
    'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
    'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
    'transparent', 'underline', 'white', 'yellow']

  valid_css_values = re.compile('^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|' +
    '\d?\.?\d?\d(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$')

  mathml_elements = ['annotation', 'annotation-xml', 'maction', 'math',
    'merror', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded',
    'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle',
    'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
    'munderover', 'none', 'semantics']

  mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign',
    'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth',
    'display', 'displaystyle', 'encoding', 'equalcolumns', 'equalrows',
    'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness',
    'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant',
    'maxsize', 'minsize', 'other', 'rowalign', 'rowalign', 'rowalign',
    'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
    'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show',
    'xlink:type', 'xmlns', 'xmlns:xlink']

  # svgtiny - foreignObject + linearGradient + radialGradient + stop - image
  svg_elements = ['a', 'animate', 'animateColor', 'animateMotion',
    'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'font-face',
    'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
    'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath',
    'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop',
    'svg', 'switch', 'text', 'title', 'tspan', 'use']

  # svgtiny + class + opacity + offset + xmlns + xmlns:xlink
  svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic',
     'arabic-form', 'ascent', 'attributeName', 'attributeType',
     'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
     'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx',
     'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity',
     'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style',
     'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2',
     'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x',
     'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines',
     'keyTimes', 'lang', 'mathematical', 'marker-end', 'marker-mid',
     'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'max',
     'min', 'name', 'offset', 'opacity', 'orient', 'origin',
     'overline-position', 'overline-thickness', 'panose-1', 'path',
     'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY',
     'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures',
     'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color',
     'stop-opacity', 'strikethrough-position', 'strikethrough-thickness',
     'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
     'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity',
     'stroke-width', 'style', 'systemLanguage', 'target', 'text-anchor', 'to',
     'transform', 'type', 'u1', 'u2', 'underline-position',
     'underline-thickness', 'unicode', 'unicode-range', 'units-per-em',
     'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x',
     'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole', 'xlink:href',
     'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base',
     'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1', 'y2',
     'zoomAndPan']

  def log(self,msg):
    offset = [self.element.line - 1 -
              self.element.dispatcher.locator.getLineNumber(),
              -self.element.dispatcher.locator.getColumnNumber()]
    self.element.log(msg, offset)

  def __init__(self,value,element):
    self.element=element
    self.valid = True
    self.parser = HTMLParser(strict=True)
    if value.lower().find('<?import ') >= 0:
      self.log(SecurityRisk({"parent":self.element.parent.name, "element":self.element.name, "tag":"?import"}))
    try:
      etree = self.parser.parseFragment(value)
      if self.valid:
        self.log(ValidHtml({"parent":self.element.parent.name, "element":self.element.name}))
      from pprint import pprint
      for tag in etree.iter():
        if tag.tag != "DOCUMENT_FRAGMENT":
          self.handle_tag(tag.tag.split('}')[-1], tag.attrib, tag.text)
    except ParseError as msg:
      element = self.element
      offset = [element.line - element.dispatcher.locator.getLineNumber(),
                - element.dispatcher.locator.getColumnNumber()]
      match = re.search(', at line (\d+), column (\d+)',str(msg))
      if match: offset[0] += int(match.group(1))-1
      element.log(NotHtml({"parent":element.parent.name, "element":element.name, "message":"Invalid HTML", "value": str(msg)}),offset)

  def handle_tag(self, tag, attributes, text):
    if tag.lower() not in self.htmltags:
      self.log(NotHtml({"parent":self.element.parent.name, "element":self.element.name,"value":tag, "message": "Non-html tag"}))
      self.valid = False
    elif tag.lower() not in HTMLValidator.acceptable_elements:
      self.log(SecurityRisk({"parent":self.element.parent.name, "element":self.element.name, "tag":tag}))
    else:
      for (name,value) in attributes.iteritems():
        if name.lower() == 'style':
          for evil in checkStyle(value):
            self.log(DangerousStyleAttr({"parent":self.element.parent.name, "element":self.element.name, "attr":"style", "value":evil}))
        elif name.lower() not in self.acceptable_attributes:
          # data-* attributes are acceptable
          if name.lower()[:5] != "data-":
            self.log(SecurityRiskAttr({"parent":self.element.parent.name, "element":self.element.name, "attr":name}))