A simple application to send CSP violation reports to an email address
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

58 lines
2.2 KiB

  1. /*
  2. * Copyright (C) 2019 bn4t
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. package main
  18. import (
  19. "fmt"
  20. "log"
  21. "net"
  22. "net/mail"
  23. "net/smtp"
  24. "time"
  25. )
  26. // sendCSPMail sends a CSP violation email to the in the config specified receiver
  27. func sendCSPMail(domain string, documentUri string, referrer string, violatedDirective string, originalPolicy string, blockedUri string) error {
  28. from := mail.Address{Name: "CSP-Handler", Address: Config.SenderEmail}
  29. body := "A CSP violation occurred for " + domain + " at " + documentUri + "\n\n**Additional info:** \nReferrer: " + referrer + "\nViolated directive: " + violatedDirective +
  30. "\nOriginal policy: " + originalPolicy + "\nBlocked URI: " + blockedUri + "\n\nThis violation happened at " + time.Now().UTC().Format(time.RFC1123Z) + "."
  31. host, _, _ := net.SplitHostPort(Config.SmtpAddress)
  32. auth := smtp.PlainAuth("", Config.SmtpUsername, Config.SmtpPassword, host)
  33. // Setup headers
  34. headers := make(map[string]string)
  35. headers["From"] = from.String()
  36. headers["To"] = Config.ReceiverEmail
  37. headers["Subject"] = "CSP violation report for " + domain
  38. headers["MIME-Version"] = "1.0"
  39. headers["Content-Type"] = "text/plain; charset=\"utf-8\""
  40. // Setup message
  41. var msg string
  42. for k, v := range headers {
  43. msg += fmt.Sprintf("%s: %s\r\n", k, v)
  44. }
  45. msg += "\r\n\r\n" + body
  46. err := smtp.SendMail(Config.SmtpAddress, auth, Config.SenderEmail, []string{Config.ReceiverEmail}, []byte(msg))
  47. if err != nil {
  48. log.Print("An error occurred while sending a csp violation mail:")
  49. log.Print(err)
  50. }
  51. return err
  52. }