ProxyLookup.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along
  14. * with this program; if not, write to the Free Software Foundation, Inc.,
  15. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. * http://www.gnu.org/copyleft/gpl.html
  17. *
  18. * @file
  19. */
  20. use Wikimedia\IPSet;
  21. /**
  22. * @since 1.28
  23. */
  24. class ProxyLookup {
  25. /**
  26. * @var string[]
  27. */
  28. private $proxyServers;
  29. /**
  30. * @var string[]
  31. */
  32. private $proxyServersComplex;
  33. /**
  34. * @var IPSet|null
  35. */
  36. private $proxyIPSet;
  37. /**
  38. * @param string[] $proxyServers Simple list of IPs
  39. * @param string[] $proxyServersComplex Complex list of IPs/ranges
  40. */
  41. public function __construct( $proxyServers, $proxyServersComplex ) {
  42. $this->proxyServers = $proxyServers;
  43. $this->proxyServersComplex = $proxyServersComplex;
  44. }
  45. /**
  46. * Checks if an IP matches a proxy we've configured
  47. *
  48. * @param string $ip
  49. * @return bool
  50. */
  51. public function isConfiguredProxy( $ip ) {
  52. // Quick check of known singular proxy servers
  53. if ( in_array( $ip, $this->proxyServers, true ) ) {
  54. return true;
  55. }
  56. // Check against addresses and CIDR nets in the complex list
  57. if ( !$this->proxyIPSet ) {
  58. $this->proxyIPSet = new IPSet( $this->proxyServersComplex );
  59. }
  60. return $this->proxyIPSet->match( $ip );
  61. }
  62. /**
  63. * Checks if an IP is a trusted proxy provider.
  64. * Useful to tell if X-Forwarded-For data is possibly bogus.
  65. * CDN cache servers for the site are whitelisted.
  66. *
  67. * @param string $ip
  68. * @return bool
  69. */
  70. public function isTrustedProxy( $ip ) {
  71. $trusted = $this->isConfiguredProxy( $ip );
  72. Hooks::run( 'IsTrustedProxy', [ &$ip, &$trusted ] );
  73. return $trusted;
  74. }
  75. }