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