github.com/webx-top/com@v1.2.12/html_xss.go (about) 1 package com 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 ) 8 9 var ( 10 defaultXSSStringForTag = `(</?)(?i)(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base%v)(\b[^>]*>)` 11 defaultXSSStringForEvent = `(<[a-zA-Z][a-zA-Z0-9]*\b[^<>]+\b)(?i)on([a-zA-Z]+)(\s*=[^<>]+>)` 12 defaultXSSStringForAttrName = `(<[a-zA-Z][a-zA-Z0-9]*\b[^<>]*\b)(?i)(style%v)(\s*=[^<>]+>)` 13 defaultXSSStringForAttrValue = `(<[a-zA-Z][a-zA-Z0-9]*\b[^<>]*\b)([a-zA-Z]+)(\s*=\s*["']*\s*)(?i)(javascript|vbscript%v)(\b[^<>]+>)` 14 15 removeXSSForTag = regexp.MustCompile(fmt.Sprintf(defaultXSSStringForTag, "")) 16 removeXSSForEvent = regexp.MustCompile(defaultXSSStringForEvent) 17 removeXSSForAttrName = regexp.MustCompile(fmt.Sprintf(defaultXSSStringForAttrName, "")) 18 removeXSSForAttrValue = regexp.MustCompile(fmt.Sprintf(defaultXSSStringForAttrValue, "")) 19 ) 20 21 // RemoveXSS 删除XSS代码 22 func RemoveXSS(v string) (r string) { 23 r = strings.Replace(v, `<!---->`, ``, -1) 24 25 //过滤HTML标签 26 r = removeXSSForTag.ReplaceAllString(r, `${1}_$2$3`) 27 28 //过滤事件属性 29 r = removeXSSForEvent.ReplaceAllString(r, `${1}_on$2$3`) 30 31 //过滤属性 32 r = removeXSSForAttrName.ReplaceAllString(r, `${1}_$2$3`) 33 34 //过滤属性值 35 r = removeXSSForAttrValue.ReplaceAllString(r, `${1}_$2${3}_$4$5`) 36 37 //fmt.Println("Execute the filter: RemoveXSS.") 38 return 39 }