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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package validation
  5. import (
  6. "net"
  7. "net/url"
  8. "strings"
  9. "code.gitea.io/gitea/modules/setting"
  10. )
  11. var loopbackIPBlocks []*net.IPNet
  12. func init() {
  13. for _, cidr := range []string{
  14. "127.0.0.0/8", // IPv4 loopback
  15. "::1/128", // IPv6 loopback
  16. } {
  17. if _, block, err := net.ParseCIDR(cidr); err == nil {
  18. loopbackIPBlocks = append(loopbackIPBlocks, block)
  19. }
  20. }
  21. }
  22. func isLoopbackIP(ip string) bool {
  23. pip := net.ParseIP(ip)
  24. if pip == nil {
  25. return false
  26. }
  27. for _, block := range loopbackIPBlocks {
  28. if block.Contains(pip) {
  29. return true
  30. }
  31. }
  32. return false
  33. }
  34. // IsValidURL checks if URL is valid
  35. func IsValidURL(uri string) bool {
  36. if u, err := url.ParseRequestURI(uri); err != nil ||
  37. (u.Scheme != "http" && u.Scheme != "https") ||
  38. !validPort(portOnly(u.Host)) {
  39. return false
  40. }
  41. return true
  42. }
  43. // IsAPIURL checks if URL is current Gitea instance API URL
  44. func IsAPIURL(uri string) bool {
  45. return strings.HasPrefix(strings.ToLower(uri), strings.ToLower(setting.AppURL+"api"))
  46. }
  47. // IsValidExternalURL checks if URL is valid external URL
  48. func IsValidExternalURL(uri string) bool {
  49. if !IsValidURL(uri) || IsAPIURL(uri) {
  50. return false
  51. }
  52. u, err := url.ParseRequestURI(uri)
  53. if err != nil {
  54. return false
  55. }
  56. // Currently check only if not loopback IP is provided to keep compatibility
  57. if isLoopbackIP(u.Hostname()) || strings.ToLower(u.Hostname()) == "localhost" {
  58. return false
  59. }
  60. // TODO: Later it should be added to allow local network IP addreses
  61. // only if allowed by special setting
  62. return true
  63. }