PageRenderTime 31ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/classes/files/curl_security_helper.php

https://github.com/mudrd8mz/moodle
PHP | 288 lines | 127 code | 25 blank | 136 comment | 41 complexity | 55bb92380515c98b58bbea40b216404a MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Contains a class providing functions used to check the allowed/blocked host/ports for curl.
  18. *
  19. * @package core
  20. * @copyright 2016 Jake Dallimore
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. * @author Jake Dallimore <jrhdallimore@gmail.com>
  23. */
  24. namespace core\files;
  25. use core\ip_utils;
  26. defined('MOODLE_INTERNAL') || exit();
  27. /**
  28. * Host and port checking for curl.
  29. *
  30. * This class provides a means to check URL/host/port against the system-level cURL security entries.
  31. * It does not provide a means to add URLs, hosts or ports to the allowed/blocked lists; this is configured manually
  32. * via the site admin section of Moodle (See: 'Site admin' > 'Security' > 'HTTP Security').
  33. *
  34. * This class is currently used by the 'curl' wrapper class in lib/filelib.php.
  35. * Depends on:
  36. * core\ip_utils (several functions)
  37. * moodlelib (clean_param)
  38. *
  39. * @package core
  40. * @copyright 2016 Jake Dallimore
  41. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42. * @author Jake Dallimore <jrhdallimore@gmail.com>
  43. */
  44. class curl_security_helper extends curl_security_helper_base {
  45. /**
  46. * @var array of supported transport schemes and their respective default ports.
  47. */
  48. protected $transportschemes = [
  49. 'http' => 80,
  50. 'https' => 443
  51. ];
  52. /**
  53. * Checks whether the given URL is blocked by checking its address and port number against the allow/block lists.
  54. * The behaviour of this function can be classified as strict, as it returns true for URLs which are invalid or
  55. * could not be parsed, as well as those valid URLs which were found in the blocklist.
  56. *
  57. * @param string $urlstring the URL to check.
  58. * @return bool true if the URL is blocked or invalid and false if the URL is not blocked.
  59. */
  60. public function url_is_blocked($urlstring) {
  61. // If no config data is present, then all hosts/ports are allowed.
  62. if (!$this->is_enabled()) {
  63. return false;
  64. }
  65. // Try to parse the URL to get the 'host' and 'port' components.
  66. try {
  67. $url = new \moodle_url($urlstring);
  68. $parsed['scheme'] = $url->get_scheme();
  69. $parsed['host'] = $url->get_host();
  70. $parsed['port'] = $url->get_port();
  71. } catch (\moodle_exception $e) {
  72. // Moodle exception is thrown if the $urlstring is invalid. Treat as blocked.
  73. return true;
  74. }
  75. // The port will be empty unless explicitly set in the $url (uncommon), so try to infer it from the supported schemes.
  76. if (!$parsed['port'] && $parsed['scheme'] && isset($this->transportschemes[$parsed['scheme']])) {
  77. $parsed['port'] = $this->transportschemes[$parsed['scheme']];
  78. }
  79. if ($parsed['port'] && $parsed['host']) {
  80. // Check the host and port against the allow/block entries.
  81. return $this->host_is_blocked($parsed['host']) || $this->port_is_blocked($parsed['port']);
  82. }
  83. return true;
  84. }
  85. /**
  86. * Returns a string message describing a blocked URL. E.g. 'This URL is blocked'.
  87. *
  88. * @return string the string error.
  89. */
  90. public function get_blocked_url_string() {
  91. return get_string('curlsecurityurlblocked', 'admin');
  92. }
  93. /**
  94. * Checks whether the host portion of a url is blocked.
  95. * The host portion may be a FQDN, IPv4 address or a IPv6 address wrapped in square brackets, as per standard URL notation.
  96. * E.g.
  97. * images.example.com
  98. * 127.0.0.1
  99. * [0.0.0.0.0.0.0.1]
  100. * The method logic is as follows:
  101. * 1. Check the host component against the list of IPv4/IPv6 addresses and ranges.
  102. * - This will perform a DNS forward lookup if required.
  103. * 2. Check the host component against the list of domain names and wildcard domain names.
  104. * - This will perform a DNS reverse lookup if required.
  105. *
  106. * The behaviour of this function can be classified as strict, as it returns true for hosts which are invalid or
  107. * could not be parsed, as well as those valid URLs which were found in the blocklist.
  108. *
  109. * @param string $host the host component of the URL to check against the blocklist.
  110. * @return bool true if the host is both valid and blocked, false otherwise.
  111. */
  112. protected function host_is_blocked($host) {
  113. if (!$this->is_enabled() || empty($host) || !is_string($host)) {
  114. return false;
  115. }
  116. // Fix for square brackets in the 'host' portion of the URL (only occurs if an IPv6 address is specified).
  117. $host = str_replace(array('[', ']'), '', $host); // RFC3986, section 3.2.2.
  118. $blockedhosts = $this->get_blocked_hosts_by_category();
  119. if (ip_utils::is_ip_address($host)) {
  120. if ($this->address_explicitly_blocked($host)) {
  121. return true;
  122. }
  123. // Only perform a reverse lookup if there is a point to it (i.e. we have rules to check against).
  124. if ($blockedhosts['domain'] || $blockedhosts['domainwildcard']) {
  125. // DNS reverse lookup - supports both IPv4 and IPv6 address formats.
  126. $hostname = gethostbyaddr($host);
  127. if ($hostname !== $host && $this->host_explicitly_blocked($hostname)) {
  128. return true;
  129. }
  130. }
  131. } else if (ip_utils::is_domain_name($host)) {
  132. if ($this->host_explicitly_blocked($host)) {
  133. return true;
  134. }
  135. // Only perform a forward lookup if there are IP rules to check against.
  136. if ($blockedhosts['ipv4'] || $blockedhosts['ipv6']) {
  137. // DNS forward lookup - returns a list of only IPv4 addresses!
  138. $hostips = $this->get_host_list_by_name($host);
  139. // If we don't get a valid record, bail (so cURL is never called).
  140. if (!$hostips) {
  141. return true;
  142. }
  143. // If any of the returned IPs are in the blocklist, block the request.
  144. foreach ($hostips as $hostip) {
  145. if ($this->address_explicitly_blocked($hostip)) {
  146. return true;
  147. }
  148. }
  149. }
  150. } else {
  151. // Was not something we consider to be a valid IP or domain name, block it.
  152. return true;
  153. }
  154. return false;
  155. }
  156. /**
  157. * Retrieve all hosts for a domain name.
  158. *
  159. * @param string $param
  160. * @return array An array of IPs associated with the host name.
  161. */
  162. protected function get_host_list_by_name($host) {
  163. return ($hostips = gethostbynamel($host)) ? $hostips : [];
  164. }
  165. /**
  166. * Checks whether the given port is blocked, as determined by its absence on the ports allowlist.
  167. * Ports are assumed to be blocked unless found in the allowlist.
  168. *
  169. * @param integer|string $port the port to check against the ports allowlist.
  170. * @return bool true if the port is blocked, false otherwise.
  171. */
  172. protected function port_is_blocked($port) {
  173. $portnum = intval($port);
  174. // Intentionally block port 0 and below and check the int cast was valid.
  175. if (empty($port) || (string)$portnum !== (string)$port || $port < 0) {
  176. return true;
  177. }
  178. $allowedports = $this->get_allowed_ports();
  179. return !empty($allowedports) && !in_array($portnum, $allowedports);
  180. }
  181. /**
  182. * Convenience method to check whether we have any entries in the host blocklist or ports allowlist admin settings.
  183. * If no entries are found at all, the assumption is that the blocklist is disabled entirely.
  184. *
  185. * @return bool true if one or more entries exist, false otherwise.
  186. */
  187. public function is_enabled() {
  188. return (!empty($this->get_allowed_ports()) || !empty($this->get_blocked_hosts()));
  189. }
  190. /**
  191. * Checks whether the input address is blocked by at any of the IPv4 or IPv6 address rules.
  192. *
  193. * @param string $addr the ip address to check.
  194. * @return bool true if the address is covered by an entry in the blocklist, false otherwise.
  195. */
  196. protected function address_explicitly_blocked($addr) {
  197. $blockedhosts = $this->get_blocked_hosts_by_category();
  198. $iphostsblocked = array_merge($blockedhosts['ipv4'], $blockedhosts['ipv6']);
  199. return address_in_subnet($addr, implode(',', $iphostsblocked));
  200. }
  201. /**
  202. * Checks whether the input hostname is blocked by any of the domain/wildcard rules.
  203. *
  204. * @param string $host the hostname to check
  205. * @return bool true if the host is covered by an entry in the blocklist, false otherwise.
  206. */
  207. protected function host_explicitly_blocked($host) {
  208. $blockedhosts = $this->get_blocked_hosts_by_category();
  209. $domainhostsblocked = array_merge($blockedhosts['domain'], $blockedhosts['domainwildcard']);
  210. return ip_utils::is_domain_in_allowed_list($host, $domainhostsblocked);
  211. }
  212. /**
  213. * Helper to get all entries from the admin setting, as an array, sorted by classification.
  214. * Classifications include 'ipv4', 'ipv6', 'domain', 'domainwildcard'.
  215. *
  216. * @return array of host/domain/ip entries from the 'curlsecurityblockedhosts' config.
  217. */
  218. protected function get_blocked_hosts_by_category() {
  219. // For each of the admin setting entries, check and place in the correct section of the config array.
  220. $config = ['ipv6' => [], 'ipv4' => [], 'domain' => [], 'domainwildcard' => []];
  221. $entries = $this->get_blocked_hosts();
  222. foreach ($entries as $entry) {
  223. if (ip_utils::is_ipv6_address($entry) || ip_utils::is_ipv6_range($entry)) {
  224. $config['ipv6'][] = $entry;
  225. } else if (ip_utils::is_ipv4_address($entry) || ip_utils::is_ipv4_range($entry)) {
  226. $config['ipv4'][] = $entry;
  227. } else if (ip_utils::is_domain_name($entry)) {
  228. $config['domain'][] = $entry;
  229. } else if (ip_utils::is_domain_matching_pattern($entry)) {
  230. $config['domainwildcard'][] = $entry;
  231. }
  232. }
  233. return $config;
  234. }
  235. /**
  236. * Helper that returns the allowed ports, as defined in the 'curlsecurityallowedport' setting.
  237. *
  238. * @return array the array of allowed ports.
  239. */
  240. protected function get_allowed_ports() {
  241. global $CFG;
  242. if (!isset($CFG->curlsecurityallowedport)) {
  243. return [];
  244. }
  245. return array_filter(array_map('trim', explode("\n", $CFG->curlsecurityallowedport)), function($entry) {
  246. return !empty($entry);
  247. });
  248. }
  249. /**
  250. * Helper that returns the blocked hosts, as defined in the 'curlsecurityblockedhosts' setting.
  251. *
  252. * @return array the array of blocked host entries.
  253. */
  254. protected function get_blocked_hosts() {
  255. global $CFG;
  256. if (!isset($CFG->curlsecurityblockedhosts)) {
  257. return [];
  258. }
  259. return array_filter(array_map('trim', explode("\n", $CFG->curlsecurityblockedhosts)), function($entry) {
  260. return !empty($entry);
  261. });
  262. }
  263. }