IpValidator.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\Html;
  11. use yii\helpers\IpHelper;
  12. use yii\helpers\Json;
  13. use yii\web\JsExpression;
  14. /**
  15. * The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet.
  16. *
  17. * It also may change attribute's value if normalization of IPv6 expansion is enabled.
  18. *
  19. * The following are examples of validation rules using this validator:
  20. *
  21. * ```php
  22. * ['ip_address', 'ip'], // IPv4 or IPv6 address
  23. * ['ip_address', 'ip', 'ipv6' => false], // IPv4 address (IPv6 is disabled)
  24. * ['ip_address', 'ip', 'subnet' => true], // requires a CIDR prefix (like 10.0.0.1/24) for the IP address
  25. * ['ip_address', 'ip', 'subnet' => null], // CIDR prefix is optional
  26. * ['ip_address', 'ip', 'subnet' => null, 'normalize' => true], // CIDR prefix is optional and will be added when missing
  27. * ['ip_address', 'ip', 'ranges' => ['192.168.0.0/24']], // only IP addresses from the specified subnet are allowed
  28. * ['ip_address', 'ip', 'ranges' => ['!192.168.0.0/24', 'any']], // any IP is allowed except IP in the specified subnet
  29. * ['ip_address', 'ip', 'expandIPv6' => true], // expands IPv6 address to a full notation format
  30. * ```
  31. *
  32. * @property array $ranges The IPv4 or IPv6 ranges that are allowed or forbidden. See [[setRanges()]] for
  33. * detailed description.
  34. *
  35. * @author Dmitry Naumenko <d.naumenko.a@gmail.com>
  36. * @since 2.0.7
  37. */
  38. class IpValidator extends Validator
  39. {
  40. /**
  41. * Negation char.
  42. *
  43. * Used to negate [[ranges]] or [[networks]] or to negate validating value when [[negation]] is set to `true`.
  44. * @see negation
  45. * @see networks
  46. * @see ranges
  47. */
  48. const NEGATION_CHAR = '!';
  49. /**
  50. * @var array The network aliases, that can be used in [[ranges]].
  51. * - key - alias name
  52. * - value - array of strings. String can be an IP range, IP address or another alias. String can be
  53. * negated with [[NEGATION_CHAR]] (independent of `negation` option).
  54. *
  55. * The following aliases are defined by default:
  56. * - `*`: `any`
  57. * - `any`: `0.0.0.0/0, ::/0`
  58. * - `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8`
  59. * - `multicast`: `224.0.0.0/4, ff00::/8`
  60. * - `linklocal`: `169.254.0.0/16, fe80::/10`
  61. * - `localhost`: `127.0.0.0/8', ::1`
  62. * - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32`
  63. * - `system`: `multicast, linklocal, localhost, documentation`
  64. */
  65. public $networks = [
  66. '*' => ['any'],
  67. 'any' => ['0.0.0.0/0', '::/0'],
  68. 'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'],
  69. 'multicast' => ['224.0.0.0/4', 'ff00::/8'],
  70. 'linklocal' => ['169.254.0.0/16', 'fe80::/10'],
  71. 'localhost' => ['127.0.0.0/8', '::1'],
  72. 'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'],
  73. 'system' => ['multicast', 'linklocal', 'localhost', 'documentation'],
  74. ];
  75. /**
  76. * @var bool whether the validating value can be an IPv6 address. Defaults to `true`.
  77. */
  78. public $ipv6 = true;
  79. /**
  80. * @var bool whether the validating value can be an IPv4 address. Defaults to `true`.
  81. */
  82. public $ipv4 = true;
  83. /**
  84. * @var bool whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`.
  85. * The following values are possible:
  86. *
  87. * - `false` - the address must not have a subnet (default).
  88. * - `true` - specifying a subnet is required.
  89. * - `null` - specifying a subnet is optional.
  90. */
  91. public $subnet = false;
  92. /**
  93. * @var bool whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an
  94. * address without it. Works only when `subnet` is not `false`. For example:
  95. * - `10.0.1.5` will normalized to `10.0.1.5/32`
  96. * - `2008:db0::1` will be normalized to `2008:db0::1/128`
  97. * Defaults to `false`.
  98. * @see subnet
  99. */
  100. public $normalize = false;
  101. /**
  102. * @var bool whether address may have a [[NEGATION_CHAR]] character at the beginning.
  103. * Defaults to `false`.
  104. */
  105. public $negation = false;
  106. /**
  107. * @var bool whether to expand an IPv6 address to the full notation format.
  108. * Defaults to `false`.
  109. */
  110. public $expandIPv6 = false;
  111. /**
  112. * @var string Regexp-pattern to validate IPv4 address
  113. */
  114. public $ipv4Pattern = '/^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9]))$/';
  115. /**
  116. * @var string Regexp-pattern to validate IPv6 address
  117. */
  118. public $ipv6Pattern = '/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/';
  119. /**
  120. * @var string user-defined error message is used when validation fails due to the wrong IP address format.
  121. *
  122. * You may use the following placeholders in the message:
  123. *
  124. * - `{attribute}`: the label of the attribute being validated
  125. * - `{value}`: the value of the attribute being validated
  126. */
  127. public $message;
  128. /**
  129. * @var string user-defined error message is used when validation fails due to the disabled IPv6 validation.
  130. *
  131. * You may use the following placeholders in the message:
  132. *
  133. * - `{attribute}`: the label of the attribute being validated
  134. * - `{value}`: the value of the attribute being validated
  135. *
  136. * @see ipv6
  137. */
  138. public $ipv6NotAllowed;
  139. /**
  140. * @var string user-defined error message is used when validation fails due to the disabled IPv4 validation.
  141. *
  142. * You may use the following placeholders in the message:
  143. *
  144. * - `{attribute}`: the label of the attribute being validated
  145. * - `{value}`: the value of the attribute being validated
  146. *
  147. * @see ipv4
  148. */
  149. public $ipv4NotAllowed;
  150. /**
  151. * @var string user-defined error message is used when validation fails due to the wrong CIDR.
  152. *
  153. * You may use the following placeholders in the message:
  154. *
  155. * - `{attribute}`: the label of the attribute being validated
  156. * - `{value}`: the value of the attribute being validated
  157. * @see subnet
  158. */
  159. public $wrongCidr;
  160. /**
  161. * @var string user-defined error message is used when validation fails due to subnet [[subnet]] set to 'only',
  162. * but the CIDR prefix is not set.
  163. *
  164. * You may use the following placeholders in the message:
  165. *
  166. * - `{attribute}`: the label of the attribute being validated
  167. * - `{value}`: the value of the attribute being validated
  168. *
  169. * @see subnet
  170. */
  171. public $noSubnet;
  172. /**
  173. * @var string user-defined error message is used when validation fails
  174. * due to [[subnet]] is false, but CIDR prefix is present.
  175. *
  176. * You may use the following placeholders in the message:
  177. *
  178. * - `{attribute}`: the label of the attribute being validated
  179. * - `{value}`: the value of the attribute being validated
  180. *
  181. * @see subnet
  182. */
  183. public $hasSubnet;
  184. /**
  185. * @var string user-defined error message is used when validation fails due to IP address
  186. * is not not allowed by [[ranges]] check.
  187. *
  188. * You may use the following placeholders in the message:
  189. *
  190. * - `{attribute}`: the label of the attribute being validated
  191. * - `{value}`: the value of the attribute being validated
  192. *
  193. * @see ranges
  194. */
  195. public $notInRange;
  196. /**
  197. * @var array
  198. */
  199. private $_ranges = [];
  200. /**
  201. * {@inheritdoc}
  202. */
  203. public function init()
  204. {
  205. parent::init();
  206. if (!$this->ipv4 && !$this->ipv6) {
  207. throw new InvalidConfigException('Both IPv4 and IPv6 checks can not be disabled at the same time');
  208. }
  209. if ($this->message === null) {
  210. $this->message = Yii::t('yii', '{attribute} must be a valid IP address.');
  211. }
  212. if ($this->ipv6NotAllowed === null) {
  213. $this->ipv6NotAllowed = Yii::t('yii', '{attribute} must not be an IPv6 address.');
  214. }
  215. if ($this->ipv4NotAllowed === null) {
  216. $this->ipv4NotAllowed = Yii::t('yii', '{attribute} must not be an IPv4 address.');
  217. }
  218. if ($this->wrongCidr === null) {
  219. $this->wrongCidr = Yii::t('yii', '{attribute} contains wrong subnet mask.');
  220. }
  221. if ($this->noSubnet === null) {
  222. $this->noSubnet = Yii::t('yii', '{attribute} must be an IP address with specified subnet.');
  223. }
  224. if ($this->hasSubnet === null) {
  225. $this->hasSubnet = Yii::t('yii', '{attribute} must not be a subnet.');
  226. }
  227. if ($this->notInRange === null) {
  228. $this->notInRange = Yii::t('yii', '{attribute} is not in the allowed range.');
  229. }
  230. }
  231. /**
  232. * Set the IPv4 or IPv6 ranges that are allowed or forbidden.
  233. *
  234. * The following preparation tasks are performed:
  235. *
  236. * - Recursively substitutes aliases (described in [[networks]]) with their values.
  237. * - Removes duplicates
  238. *
  239. * @property array the IPv4 or IPv6 ranges that are allowed or forbidden.
  240. * See [[setRanges()]] for detailed description.
  241. * @param array $ranges the IPv4 or IPv6 ranges that are allowed or forbidden.
  242. *
  243. * When the array is empty, or the option not set, all IP addresses are allowed.
  244. *
  245. * Otherwise, the rules are checked sequentially until the first match is found.
  246. * An IP address is forbidden, when it has not matched any of the rules.
  247. *
  248. * Example:
  249. *
  250. * ```php
  251. * [
  252. * 'ranges' => [
  253. * '192.168.10.128'
  254. * '!192.168.10.0/24',
  255. * 'any' // allows any other IP addresses
  256. * ]
  257. * ]
  258. * ```
  259. *
  260. * In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24` subnet.
  261. * IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction.
  262. */
  263. public function setRanges($ranges)
  264. {
  265. $this->_ranges = $this->prepareRanges((array) $ranges);
  266. }
  267. /**
  268. * @return array The IPv4 or IPv6 ranges that are allowed or forbidden.
  269. */
  270. public function getRanges()
  271. {
  272. return $this->_ranges;
  273. }
  274. /**
  275. * {@inheritdoc}
  276. */
  277. protected function validateValue($value)
  278. {
  279. $result = $this->validateSubnet($value);
  280. if (is_array($result)) {
  281. $result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
  282. return $result;
  283. }
  284. return null;
  285. }
  286. /**
  287. * {@inheritdoc}
  288. */
  289. public function validateAttribute($model, $attribute)
  290. {
  291. $value = $model->$attribute;
  292. $result = $this->validateSubnet($value);
  293. if (is_array($result)) {
  294. $result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
  295. $this->addError($model, $attribute, $result[0], $result[1]);
  296. } else {
  297. $model->$attribute = $result;
  298. }
  299. }
  300. /**
  301. * Validates an IPv4/IPv6 address or subnet.
  302. *
  303. * @param $ip string
  304. * @return string|array
  305. * string - the validation was successful;
  306. * array - an error occurred during the validation.
  307. * Array[0] contains the text of an error, array[1] contains values for the placeholders in the error message
  308. */
  309. private function validateSubnet($ip)
  310. {
  311. if (!is_string($ip)) {
  312. return [$this->message, []];
  313. }
  314. $negation = null;
  315. $cidr = null;
  316. $isCidrDefault = false;
  317. if (preg_match($this->getIpParsePattern(), $ip, $matches)) {
  318. $negation = ($matches[1] !== '') ? $matches[1] : null;
  319. $ip = $matches[2];
  320. $cidr = isset($matches[4]) ? $matches[4] : null;
  321. }
  322. if ($this->subnet === true && $cidr === null) {
  323. return [$this->noSubnet, []];
  324. }
  325. if ($this->subnet === false && $cidr !== null) {
  326. return [$this->hasSubnet, []];
  327. }
  328. if ($this->negation === false && $negation !== null) {
  329. return [$this->message, []];
  330. }
  331. if ($this->getIpVersion($ip) === IpHelper::IPV6) {
  332. if ($cidr !== null) {
  333. if ($cidr > IpHelper::IPV6_ADDRESS_LENGTH || $cidr < 0) {
  334. return [$this->wrongCidr, []];
  335. }
  336. } else {
  337. $isCidrDefault = true;
  338. $cidr = IpHelper::IPV6_ADDRESS_LENGTH;
  339. }
  340. if (!$this->validateIPv6($ip)) {
  341. return [$this->message, []];
  342. }
  343. if (!$this->ipv6) {
  344. return [$this->ipv6NotAllowed, []];
  345. }
  346. if ($this->expandIPv6) {
  347. $ip = $this->expandIPv6($ip);
  348. }
  349. } else {
  350. if ($cidr !== null) {
  351. if ($cidr > IpHelper::IPV4_ADDRESS_LENGTH || $cidr < 0) {
  352. return [$this->wrongCidr, []];
  353. }
  354. } else {
  355. $isCidrDefault = true;
  356. $cidr = IpHelper::IPV4_ADDRESS_LENGTH;
  357. }
  358. if (!$this->validateIPv4($ip)) {
  359. return [$this->message, []];
  360. }
  361. if (!$this->ipv4) {
  362. return [$this->ipv4NotAllowed, []];
  363. }
  364. }
  365. if (!$this->isAllowed($ip, $cidr)) {
  366. return [$this->notInRange, []];
  367. }
  368. $result = $negation . $ip;
  369. if ($this->subnet !== false && (!$isCidrDefault || $isCidrDefault && $this->normalize)) {
  370. $result .= "/$cidr";
  371. }
  372. return $result;
  373. }
  374. /**
  375. * Expands an IPv6 address to it's full notation.
  376. *
  377. * For example `2001:db8::1` will be expanded to `2001:0db8:0000:0000:0000:0000:0000:0001`.
  378. *
  379. * @param string $ip the original IPv6
  380. * @return string the expanded IPv6
  381. */
  382. private function expandIPv6($ip)
  383. {
  384. return IpHelper::expandIPv6($ip);
  385. }
  386. /**
  387. * The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list.
  388. *
  389. * @param string $ip
  390. * @param int $cidr
  391. * @return bool
  392. * @see ranges
  393. */
  394. private function isAllowed($ip, $cidr)
  395. {
  396. if (empty($this->ranges)) {
  397. return true;
  398. }
  399. foreach ($this->ranges as $string) {
  400. list($isNegated, $range) = $this->parseNegatedRange($string);
  401. if ($this->inRange($ip, $cidr, $range)) {
  402. return !$isNegated;
  403. }
  404. }
  405. return false;
  406. }
  407. /**
  408. * Parses IP address/range for the negation with [[NEGATION_CHAR]].
  409. *
  410. * @param $string
  411. * @return array `[0 => bool, 1 => string]`
  412. * - boolean: whether the string is negated
  413. * - string: the string without negation (when the negation were present)
  414. */
  415. private function parseNegatedRange($string)
  416. {
  417. $isNegated = strpos($string, static::NEGATION_CHAR) === 0;
  418. return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
  419. }
  420. /**
  421. * Prepares array to fill in [[ranges]].
  422. *
  423. * - Recursively substitutes aliases, described in [[networks]] with their values,
  424. * - Removes duplicates.
  425. *
  426. * @param $ranges
  427. * @return array
  428. * @see networks
  429. */
  430. private function prepareRanges($ranges)
  431. {
  432. $result = [];
  433. foreach ($ranges as $string) {
  434. list($isRangeNegated, $range) = $this->parseNegatedRange($string);
  435. if (isset($this->networks[$range])) {
  436. $replacements = $this->prepareRanges($this->networks[$range]);
  437. foreach ($replacements as &$replacement) {
  438. list($isReplacementNegated, $replacement) = $this->parseNegatedRange($replacement);
  439. $result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
  440. }
  441. } else {
  442. $result[] = $string;
  443. }
  444. }
  445. return array_unique($result);
  446. }
  447. /**
  448. * Validates IPv4 address.
  449. *
  450. * @param string $value
  451. * @return bool
  452. */
  453. protected function validateIPv4($value)
  454. {
  455. return preg_match($this->ipv4Pattern, $value) !== 0;
  456. }
  457. /**
  458. * Validates IPv6 address.
  459. *
  460. * @param string $value
  461. * @return bool
  462. */
  463. protected function validateIPv6($value)
  464. {
  465. return preg_match($this->ipv6Pattern, $value) !== 0;
  466. }
  467. /**
  468. * Gets the IP version.
  469. *
  470. * @param string $ip
  471. * @return int
  472. */
  473. private function getIpVersion($ip)
  474. {
  475. return IpHelper::getIpVersion($ip);
  476. }
  477. /**
  478. * Used to get the Regexp pattern for initial IP address parsing.
  479. * @return string
  480. */
  481. private function getIpParsePattern()
  482. {
  483. return '/^(' . preg_quote(static::NEGATION_CHAR, '/') . '?)(.+?)(\/(\d+))?$/';
  484. }
  485. /**
  486. * Checks whether the IP is in subnet range.
  487. *
  488. * @param string $ip an IPv4 or IPv6 address
  489. * @param int $cidr
  490. * @param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64`
  491. * @return bool
  492. */
  493. private function inRange($ip, $cidr, $range)
  494. {
  495. return IpHelper::inRange($ip . '/' . $cidr, $range);
  496. }
  497. /**
  498. * {@inheritdoc}
  499. */
  500. public function clientValidateAttribute($model, $attribute, $view)
  501. {
  502. ValidationAsset::register($view);
  503. $options = $this->getClientOptions($model, $attribute);
  504. return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');';
  505. }
  506. /**
  507. * {@inheritdoc}
  508. */
  509. public function getClientOptions($model, $attribute)
  510. {
  511. $messages = [
  512. 'ipv6NotAllowed' => $this->ipv6NotAllowed,
  513. 'ipv4NotAllowed' => $this->ipv4NotAllowed,
  514. 'message' => $this->message,
  515. 'noSubnet' => $this->noSubnet,
  516. 'hasSubnet' => $this->hasSubnet,
  517. ];
  518. foreach ($messages as &$message) {
  519. $message = $this->formatMessage($message, [
  520. 'attribute' => $model->getAttributeLabel($attribute),
  521. ]);
  522. }
  523. $options = [
  524. 'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv4Pattern)),
  525. 'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv6Pattern)),
  526. 'messages' => $messages,
  527. 'ipv4' => (bool) $this->ipv4,
  528. 'ipv6' => (bool) $this->ipv6,
  529. 'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($this->getIpParsePattern())),
  530. 'negation' => $this->negation,
  531. 'subnet' => $this->subnet,
  532. ];
  533. if ($this->skipOnEmpty) {
  534. $options['skipOnEmpty'] = 1;
  535. }
  536. return $options;
  537. }
  538. }