geturl.lib.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. /* Copyright (C) 2008-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program 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. * This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
  16. * or see https://www.gnu.org/
  17. */
  18. /**
  19. * \file htdocs/core/lib/geturl.lib.php
  20. * \brief This file contains functions dedicated to get URLs.
  21. */
  22. /**
  23. * Function to get a content from an URL (use proxy if proxy defined).
  24. * Support Dolibarr setup for timeout and proxy.
  25. * Enhancement of CURL to add an anti SSRF protection:
  26. * - you can set MAIN_SECURITY_ANTI_SSRF_SERVER_IP to set static ip of server
  27. * - common local lookup ips like 127.*.*.* are automatically added
  28. *
  29. * @param string $url URL to call.
  30. * @param string $postorget 'POST', 'GET', 'HEAD', 'PUT', 'PUTALREADYFORMATED', 'POSTALREADYFORMATED', 'DELETE'
  31. * @param string $param Parameters of URL (x=value1&y=value2) or may be a formated content with $postorget='PUTALREADYFORMATED'
  32. * @param integer $followlocation 0=Do not follow, 1=Follow location.
  33. * @param string[] $addheaders Array of string to add into header. Example: ('Accept: application/xrds+xml', ....)
  34. * @param string[] $allowedschemes List of schemes that are allowed ('http' + 'https' only by default)
  35. * @param int $localurl 0=Only external URL are possible, 1=Only local URL, 2=Both external and local URL are allowed.
  36. * @return array Returns an associative array containing the response from the server array('content'=>response, 'curl_error_no'=>errno, 'curl_error_msg'=>errmsg...)
  37. */
  38. function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = 1, $addheaders = array(), $allowedschemes = array('http', 'https'), $localurl = 0)
  39. {
  40. //declaring of global variables
  41. global $conf;
  42. $USE_PROXY = empty($conf->global->MAIN_PROXY_USE) ? 0 : $conf->global->MAIN_PROXY_USE;
  43. $PROXY_HOST = empty($conf->global->MAIN_PROXY_HOST) ? 0 : $conf->global->MAIN_PROXY_HOST;
  44. $PROXY_PORT = empty($conf->global->MAIN_PROXY_PORT) ? 0 : $conf->global->MAIN_PROXY_PORT;
  45. $PROXY_USER = empty($conf->global->MAIN_PROXY_USER) ? 0 : $conf->global->MAIN_PROXY_USER;
  46. $PROXY_PASS = empty($conf->global->MAIN_PROXY_PASS) ? 0 : $conf->global->MAIN_PROXY_PASS;
  47. dol_syslog("getURLContent postorget=".$postorget." URL=".$url." param=".$param);
  48. //setting the curl parameters.
  49. $ch = curl_init();
  50. /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."<br>";
  51. print $USE_PROXY."-".$gv_ApiErrorURL."<br>";
  52. print $nvpStr;
  53. exit;*/
  54. curl_setopt($ch, CURLOPT_VERBOSE, 1);
  55. curl_setopt($ch, CURLOPT_USERAGENT, 'Dolibarr geturl function');
  56. // We use @ here because this may return warning if safe mode is on or open_basedir is on (following location is forbidden when safe mode is on).
  57. // We force value to false so we will manage redirection ourself later.
  58. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
  59. if (is_array($addheaders) && count($addheaders)) {
  60. curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders);
  61. }
  62. curl_setopt($ch, CURLINFO_HEADER_OUT, true); // To be able to retrieve request header and log it
  63. // By default use tls decied by PHP.
  64. // You can force, if supported a version like TLSv1 or TLSv1.2
  65. if (!empty($conf->global->MAIN_CURL_SSLVERSION)) {
  66. curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION);
  67. }
  68. //curl_setopt($ch, CURLOPT_SSLVERSION, 6); for tls 1.2
  69. // Turning off the server and peer verification(TrustManager Concept).
  70. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  71. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  72. // Restrict use to some protocols only
  73. $protocols = 0;
  74. if (is_array($allowedschemes)) {
  75. foreach ($allowedschemes as $allowedscheme) {
  76. if ($allowedscheme == 'http') {
  77. $protocols |= CURLPROTO_HTTP;
  78. }
  79. if ($allowedscheme == 'https') {
  80. $protocols |= CURLPROTO_HTTPS;
  81. }
  82. }
  83. curl_setopt($ch, CURLOPT_PROTOCOLS, $protocols);
  84. curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, $protocols);
  85. }
  86. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 5 : $conf->global->MAIN_USE_CONNECT_TIMEOUT);
  87. curl_setopt($ch, CURLOPT_TIMEOUT, empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
  88. //curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); // PHP 5.5
  89. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // We want response
  90. if ($postorget == 'POST') {
  91. curl_setopt($ch, CURLOPT_POST, 1); // POST
  92. curl_setopt($ch, CURLOPT_POSTFIELDS, $param); // Setting param x=a&y=z as POST fields
  93. } elseif ($postorget == 'POSTALREADYFORMATED') {
  94. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); // HTTP request is 'POST' but param string is taken as it is
  95. curl_setopt($ch, CURLOPT_POSTFIELDS, $param); // param = content of post, like a xml string
  96. } elseif ($postorget == 'PUT') {
  97. $array_param = null;
  98. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // HTTP request is 'PUT'
  99. if (!is_array($param)) {
  100. parse_str($param, $array_param);
  101. } else {
  102. dol_syslog("parameter param must be a string", LOG_WARNING);
  103. $array_param = $param;
  104. }
  105. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array_param)); // Setting param x=a&y=z as PUT fields
  106. } elseif ($postorget == 'PUTALREADYFORMATED') {
  107. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // HTTP request is 'PUT'
  108. curl_setopt($ch, CURLOPT_POSTFIELDS, $param); // param = content of post, like a xml string
  109. } elseif ($postorget == 'HEAD') {
  110. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
  111. curl_setopt($ch, CURLOPT_NOBODY, true);
  112. } elseif ($postorget == 'DELETE') {
  113. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); // POST
  114. } else {
  115. curl_setopt($ch, CURLOPT_POST, 0); // GET
  116. }
  117. //if USE_PROXY constant set at begin of this method.
  118. if ($USE_PROXY) {
  119. dol_syslog("getURLContent set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS);
  120. //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10
  121. curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
  122. if ($PROXY_USER) {
  123. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS);
  124. }
  125. }
  126. $newUrl = $url;
  127. $maxRedirection = 5;
  128. $info = array();
  129. $response = '';
  130. do {
  131. if ($maxRedirection < 1) {
  132. break;
  133. }
  134. curl_setopt($ch, CURLOPT_URL, $newUrl);
  135. // Parse $newUrl
  136. $newUrlArray = parse_url($newUrl);
  137. $hosttocheck = $newUrlArray['host'];
  138. $hosttocheck = str_replace(array('[', ']'), '', $hosttocheck); // Remove brackets of IPv6
  139. // Deny some reserved host names
  140. if (in_array($hosttocheck, array('metadata.google.internal'))) {
  141. $info['http_code'] = 400;
  142. $info['content'] = 'Error bad hostname '.$hosttocheck.' (Used by Google metadata). This value for hostname is not allowed.';
  143. break;
  144. }
  145. // Clean host name $hosttocheck to convert it into an IP $iptocheck
  146. if (in_array($hosttocheck, array('localhost', 'localhost.domain'))) {
  147. $iptocheck = '127.0.0.1';
  148. } elseif (in_array($hosttocheck, array('ip6-localhost', 'ip6-loopback'))) {
  149. $iptocheck = '::1';
  150. } else {
  151. // Resolve $hosttocheck to get the IP $iptocheck and set CURLOPT_CONNECT_TO to use this ip so curl will not try another resolution that may give a different result
  152. if (function_exists('gethostbyname')) {
  153. $iptocheck = gethostbyname($hosttocheck);
  154. } else {
  155. $iptocheck = $hosttocheck;
  156. }
  157. // TODO Resolve ip v6
  158. }
  159. // Check $iptocheck is an IP (v4 or v6), if not clear value.
  160. if (!filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) { // This is not an IP, we clean data
  161. $iptocheck = '0'; //
  162. }
  163. if ($iptocheck) {
  164. if ($localurl == 0) { // Only external url allowed (dangerous, may allow to get malware)
  165. if (!filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  166. // Deny ips like 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 et 240.0.0.0/4, ::1/128, ::/128, ::ffff:0:0/96, fe80::/10...
  167. $info['http_code'] = 400;
  168. $info['content'] = 'Error bad hostname IP (private or reserved range). Must be an external URL.';
  169. break;
  170. }
  171. if (!empty($_SERVER["SERVER_ADDR"]) && $iptocheck == $_SERVER["SERVER_ADDR"]) {
  172. $info['http_code'] = 400;
  173. $info['content'] = 'Error bad hostname IP (IP is a local IP). Must be an external URL.';
  174. break;
  175. }
  176. if (!empty($conf->global->MAIN_SECURITY_ANTI_SSRF_SERVER_IP) && in_array($iptocheck, explode(',', $conf->global->MAIN_SECURITY_ANTI_SSRF_SERVER_IP))) {
  177. $info['http_code'] = 400;
  178. $info['content'] = 'Error bad hostname IP (IP is a local IP defined into MAIN_SECURITY_SERVER_IP). Must be an external URL.';
  179. break;
  180. }
  181. }
  182. if ($localurl == 1) { // Only local url allowed (dangerous, may allow to get metadata on server or make internal port scanning)
  183. // Deny ips NOT like 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 et 240.0.0.0/4, ::1/128, ::/128, ::ffff:0:0/96, fe80::/10...
  184. if (filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  185. $info['http_code'] = 400;
  186. $info['content'] = 'Error bad hostname '.$iptocheck.'. Must be a local URL.';
  187. break;
  188. }
  189. if (!empty($conf->global->MAIN_SECURITY_ANTI_SSRF_SERVER_IP) && !in_array($iptocheck, explode(',', $conf->global->MAIN_SECURITY_ANTI_SSRF_SERVER_IP))) {
  190. $info['http_code'] = 400;
  191. $info['content'] = 'Error bad hostname IP (IP is not a local IP defined into list MAIN_SECURITY_SERVER_IP). Must be a local URL in allowed list.';
  192. break;
  193. }
  194. }
  195. // Common check on ip (local and external)
  196. $arrayofmetadataserver = array('100.100.100.200' => 'Alibaba', '192.0.0.192'=> 'Oracle', '192.80.8.124'=>'Packet');
  197. foreach ($arrayofmetadataserver as $ipofmetadataserver => $nameofmetadataserver) {
  198. if ($iptocheck == $ipofmetadataserver) {
  199. $info['http_code'] = 400;
  200. $info['content'] = 'Error bad hostname IP (Used by '.$nameofmetadataserver.' metadata server). This IP is forbidden.';
  201. break 2; // exit the foreach and the do...
  202. }
  203. }
  204. // Set CURLOPT_CONNECT_TO so curl will not try another resolution that may give a different result. Possible only on PHP v7+
  205. if (defined('CURLOPT_CONNECT_TO')) {
  206. $connect_to = array(sprintf("%s:%d:%s:%d", $newUrlArray['host'], empty($newUrlArray['port'])?'':$newUrlArray['port'], $iptocheck, empty($newUrlArray['port'])?'':$newUrlArray['port']));
  207. //var_dump($newUrlArray);
  208. //var_dump($connect_to);
  209. curl_setopt($ch, CURLOPT_CONNECT_TO, $connect_to);
  210. }
  211. }
  212. // Getting response from server
  213. $response = curl_exec($ch);
  214. $info = curl_getinfo($ch); // Reading of request must be done after sending request
  215. $http_code = $info['http_code'];
  216. if ($followlocation && ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307)) {
  217. $newUrl = $info['redirect_url'];
  218. $maxRedirection--;
  219. // TODO Use $info['local_ip'] and $info['primary_ip'] ?
  220. continue;
  221. } else {
  222. $http_code = 0;
  223. }
  224. } while ($http_code);
  225. $request = curl_getinfo($ch, CURLINFO_HEADER_OUT); // Reading of request must be done after sending request
  226. dol_syslog("getURLContent request=".$request);
  227. if (!empty($conf->global->MAIN_GETURLCONTENT_OUTPUT_RESPONSE)) {
  228. // This may contains binary data, so we dont output reponse by default.
  229. dol_syslog("getURLContent response =".$response);
  230. }
  231. dol_syslog("getURLContent response size=".strlen($response)); // This may contains binary data, so we dont output it
  232. $rep = array();
  233. if (curl_errno($ch)) {
  234. // Add keys to $rep
  235. $rep['content'] = $response;
  236. // moving to display page to display curl errors
  237. $rep['curl_error_no'] = curl_errno($ch);
  238. $rep['curl_error_msg'] = curl_error($ch);
  239. dol_syslog("getURLContent response array is ".join(',', $rep));
  240. } else {
  241. //$info = curl_getinfo($ch);
  242. // Add keys to $rep
  243. $rep = $info;
  244. //$rep['header_size']=$info['header_size'];
  245. //$rep['http_code']=$info['http_code'];
  246. dol_syslog("getURLContent http_code=".$rep['http_code']);
  247. // Add more keys to $rep
  248. if ($response) {
  249. $rep['content'] = $response;
  250. }
  251. $rep['curl_error_no'] = '';
  252. $rep['curl_error_msg'] = '';
  253. }
  254. //closing the curl
  255. curl_close($ch);
  256. return $rep;
  257. }
  258. /**
  259. * Function get second level domain name.
  260. * For example: https://www.abc.mydomain.com/dir/page.html return 'mydomain'
  261. *
  262. * @param string $url Full URL.
  263. * @param int $mode 0=return 'mydomain', 1=return 'mydomain.com', 2=return 'abc.mydomain.com'
  264. * @return string Returns domaine name
  265. */
  266. function getDomainFromURL($url, $mode = 0)
  267. {
  268. $tmpdomain = preg_replace('/^https?:\/\//i', '', $url); // Remove http(s)://
  269. $tmpdomain = preg_replace('/\/.*$/i', '', $tmpdomain); // Remove part after domain
  270. if ($mode == 2) {
  271. $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)\.([^\.]+)$/', '\1.\2.\3', $tmpdomain); // Remove part 'www.' before 'abc.mydomain.com'
  272. } else {
  273. $tmpdomain = preg_replace('/^.*\.([^\.]+)\.([^\.]+)$/', '\1.\2', $tmpdomain); // Remove part 'www.abc.' before 'mydomain.com'
  274. }
  275. if (empty($mode)) {
  276. $tmpdomain = preg_replace('/\.[^\.]+$/', '', $tmpdomain); // Remove first level domain (.com, .net, ...)
  277. }
  278. return $tmpdomain;
  279. }
  280. /**
  281. * Function root url from a long url
  282. * For example: https://www.abc.mydomain.com/dir/page.html return 'https://www.abc.mydomain.com'
  283. * For example: http://www.abc.mydomain.com/ return 'https://www.abc.mydomain.com'
  284. *
  285. * @param string $url Full URL.
  286. * @return string Returns root url
  287. */
  288. function getRootURLFromURL($url)
  289. {
  290. $prefix = '';
  291. $tmpurl = $url;
  292. $reg = null;
  293. if (preg_match('/^(https?:\/\/)/i', $tmpurl, $reg)) {
  294. $prefix = $reg[1];
  295. }
  296. $tmpurl = preg_replace('/^https?:\/\//i', '', $tmpurl); // Remove http(s)://
  297. $tmpurl = preg_replace('/\/.*$/i', '', $tmpurl); // Remove part after domain
  298. return $prefix.$tmpurl;
  299. }
  300. /**
  301. * Function to remove comments into HTML content
  302. *
  303. * @param string $content Text content
  304. * @return string Returns text without HTML comments
  305. */
  306. function removeHtmlComment($content)
  307. {
  308. $content = preg_replace('/<!--[^\-]+-->/', '', $content);
  309. return $content;
  310. }