source.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package security
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "github.com/imgproxy/imgproxy/v3/config"
  7. "github.com/imgproxy/imgproxy/v3/ierrors"
  8. )
  9. var ErrSourceAddressNotAllowed = errors.New("source address is not allowed")
  10. var ErrInvalidSourceAddress = errors.New("invalid source address")
  11. func VerifySourceURL(imageURL string) error {
  12. if len(config.AllowedSources) == 0 {
  13. return nil
  14. }
  15. for _, allowedSource := range config.AllowedSources {
  16. if allowedSource.MatchString(imageURL) {
  17. return nil
  18. }
  19. }
  20. return ierrors.New(
  21. 404,
  22. fmt.Sprintf("Source URL is not allowed: %s", imageURL),
  23. "Invalid source",
  24. )
  25. }
  26. func VerifySourceNetwork(addr string) error {
  27. host, _, err := net.SplitHostPort(addr)
  28. if err != nil {
  29. host = addr
  30. }
  31. ip := net.ParseIP(host)
  32. if ip == nil {
  33. return ErrInvalidSourceAddress
  34. }
  35. if !config.AllowLoopbackSourceAddresses && ip.IsLoopback() {
  36. return ErrSourceAddressNotAllowed
  37. }
  38. if !config.AllowLinkLocalSourceAddresses && (ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()) {
  39. return ErrSourceAddressNotAllowed
  40. }
  41. if !config.AllowPrivateSourceAddresses && ip.IsPrivate() {
  42. return ErrSourceAddressNotAllowed
  43. }
  44. return nil
  45. }