log.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //Package for a safer logging wrapper around the standard logging package
  2. //import "git.torproject.org/pluggable-transports/snowflake.git/common/safelog"
  3. package safelog
  4. import (
  5. "bytes"
  6. "io"
  7. "regexp"
  8. )
  9. const ipv4Address = `\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`
  10. const ipv6Address = `([0-9a-fA-F]{0,4}:){5,7}([0-9a-fA-F]{0,4})?`
  11. const ipv6Compressed = `([0-9a-fA-F]{0,4}:){0,5}([0-9a-fA-F]{0,4})?(::)([0-9a-fA-F]{0,4}:){0,5}([0-9a-fA-F]{0,4})?`
  12. const ipv6Full = `(` + ipv6Address + `(` + ipv4Address + `))` +
  13. `|(` + ipv6Compressed + `(` + ipv4Address + `))` +
  14. `|(` + ipv6Address + `)` + `|(` + ipv6Compressed + `)`
  15. const optionalPort = `(:\d{1,5})?`
  16. const addressPattern = `((` + ipv4Address + `)|(\[(` + ipv6Full + `)\])|(` + ipv6Full + `))` + optionalPort
  17. const fullAddrPattern = `(^|\s|[^\w:])` + addressPattern + `(\s|(:\s)|[^\w:]|$)`
  18. var scrubberPatterns = []*regexp.Regexp{
  19. regexp.MustCompile(fullAddrPattern),
  20. }
  21. var addressRegexp = regexp.MustCompile(addressPattern)
  22. // An io.Writer that can be used as the output for a logger that first
  23. // sanitizes logs and then writes to the provided io.Writer
  24. type LogScrubber struct {
  25. Output io.Writer
  26. buffer []byte
  27. }
  28. func scrub(b []byte) []byte {
  29. scrubbedBytes := b
  30. for _, pattern := range scrubberPatterns {
  31. // this is a workaround since go does not yet support look ahead or look
  32. // behind for regular expressions.
  33. scrubbedBytes = pattern.ReplaceAllFunc(scrubbedBytes, func(b []byte) []byte {
  34. return addressRegexp.ReplaceAll(b, []byte("[scrubbed]"))
  35. })
  36. }
  37. return scrubbedBytes
  38. }
  39. func (ls *LogScrubber) Write(b []byte) (n int, err error) {
  40. n = len(b)
  41. ls.buffer = append(ls.buffer, b...)
  42. for {
  43. i := bytes.LastIndexByte(ls.buffer, '\n')
  44. if i == -1 {
  45. return
  46. }
  47. fullLines := ls.buffer[:i+1]
  48. _, err = ls.Output.Write(scrub(fullLines))
  49. if err != nil {
  50. return
  51. }
  52. ls.buffer = ls.buffer[i+1:]
  53. }
  54. }