Browse Source

Add tags sanitizer for rich text body

- Remove "bad" tags from message body before display in web
  interface
Alexey Edelev 4 years ago
parent
commit
d5006edcc2
2 changed files with 28 additions and 1 deletions
  1. 25 1
      utils/string.go
  2. 3 0
      web/mail.go

+ 25 - 1
utils/string.go

@@ -25,8 +25,32 @@
 
 package utils
 
-import "strings"
+import (
+	"regexp"
+	"strings"
+)
 
 func StartsWith(s, key string) bool {
 	return strings.Index(s, key) == 0
 }
+
+func RemoveSubString(text *string, begin string, end string) {
+	headIndex := strings.Index(*text, begin)
+	if headIndex >= 0 {
+		headEndIndex := strings.Index(*text, end)
+		runes := []rune(*text)
+		runes = append(runes[0:headIndex], runes[headEndIndex+len(end):]...)
+		*text = string(runes)
+	}
+}
+
+func SanitizeTags(text *string) {
+	re := regexp.MustCompile(`</?html[^<>]*>`)
+	*text = string(re.ReplaceAll([]byte(*text), []byte{}))
+
+	re = regexp.MustCompile(`</?body[^<>]*>`)
+	*text = string(re.ReplaceAll([]byte(*text), []byte{}))
+
+	RemoveSubString(text, "<head", "/head>")
+	RemoveSubString(text, "<style", "/style>")
+}

+ 3 - 0
web/mail.go

@@ -33,6 +33,7 @@ import (
 	"strings"
 
 	"git.semlanik.org/semlanik/gostfix/common"
+	"git.semlanik.org/semlanik/gostfix/utils"
 )
 
 func (s *Server) handleMailRequest(w http.ResponseWriter, r *http.Request) {
@@ -73,6 +74,8 @@ func (s *Server) handleMailDetails(w http.ResponseWriter, user, mailId string) {
 	text := mail.Mail.Body.RichText
 	if text == "" {
 		text = strings.Replace(mail.Mail.Body.PlainText, "\n", "</br>", -1)
+	} else {
+		utils.SanitizeTags(&text)
 	}
 
 	s.storage.SetRead(user, mailId, true)