auth.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. <?php
  2. /**
  3. * auth.php
  4. *
  5. * Contains functions used to do authentication.
  6. *
  7. * Dependencies:
  8. * functions/global.php
  9. * functions/strings.php.
  10. *
  11. * @copyright 1999-2025 The SquirrelMail Project Team
  12. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  13. * @version $Id$
  14. * @package squirrelmail
  15. */
  16. /**
  17. * Detect whether user is logged in
  18. *
  19. * Function is similar to is_logged_in() function. If user is logged in, function
  20. * returns true. If user is not logged in or session is expired, function saves $_POST
  21. * and PAGE_NAME in session and returns false. POST information is saved in
  22. * 'session_expired_post' variable, PAGE_NAME is saved in 'session_expired_location'.
  23. *
  24. * This function optionally checks the referrer of this page request. If the
  25. * administrator wants to impose a check that the referrer of this page request
  26. * is another page on the same domain (otherwise, the page request is likely
  27. * the result of a XSS or phishing attack), then they need to specify the
  28. * acceptable referrer domain in a variable named $check_referrer in
  29. * config/config.php (or the configuration tool) for which the value is
  30. * usually the same as the $domain setting (for example:
  31. * $check_referrer = 'example.com';
  32. * However, in some cases (where proxy servers are in use, etc.), the
  33. * acceptable referrer might be different. If $check_referrer is set to
  34. * "###DOMAIN###", then the current value of $domain is used (useful in
  35. * situations where $domain might change at runtime (when using the Login
  36. * Manager plugin to host multiple domains with one SquirrelMail installation,
  37. * for example)):
  38. * $check_referrer = '###DOMAIN###';
  39. * NOTE HOWEVER, that referrer checks are not foolproof - they can be spoofed
  40. * by browsers, and some browsers intentionally don't send them, in which
  41. * case SquirrelMail silently ignores referrer checks.
  42. *
  43. * Script that uses this function instead of is_logged_in() function, must handle user
  44. * level messages.
  45. * @return boolean
  46. * @since 1.5.1
  47. */
  48. function sqauth_is_logged_in() {
  49. global $check_referrer, $domain;
  50. if (!sqgetGlobalVar('HTTP_REFERER', $referrer, SQ_SERVER)) $referrer = '';
  51. if ($check_referrer == '###DOMAIN###') $check_referrer = $domain;
  52. if (!empty($check_referrer)) {
  53. $ssl_check_referrer = 'https://' . $check_referrer;
  54. $plain_check_referrer = 'http://' . $check_referrer;
  55. }
  56. if (sqsession_is_registered('user_is_logged_in')
  57. && (!$check_referrer || empty($referrer)
  58. || ($check_referrer && !empty($referrer)
  59. && (strpos(strtolower($referrer), strtolower($plain_check_referrer)) === 0
  60. || strpos(strtolower($referrer), strtolower($ssl_check_referrer)) === 0)))) {
  61. return true;
  62. }
  63. // First we store some information in the new session to prevent
  64. // information-loss.
  65. $session_expired_post = $_POST;
  66. if (defined('PAGE_NAME'))
  67. $session_expired_location = PAGE_NAME;
  68. else
  69. $session_expired_location = '';
  70. if (!sqsession_is_registered('session_expired_post')) {
  71. sqsession_register($session_expired_post,'session_expired_post');
  72. }
  73. if (!sqsession_is_registered('session_expired_location')) {
  74. sqsession_register($session_expired_location,'session_expired_location');
  75. }
  76. session_write_close();
  77. return false;
  78. }
  79. /**
  80. * Reads and decodes stored user password information
  81. *
  82. * Direct access to password information is deprecated.
  83. * @return string password in plain text
  84. * @since 1.5.1
  85. */
  86. function sqauth_read_password() {
  87. global $currentHookName;
  88. if ($currentHookName == 'login_verified') global $key;
  89. sqgetGlobalVar('key', $key, SQ_COOKIE);
  90. sqgetGlobalVar('onetimepad', $onetimepad,SQ_SESSION);
  91. return OneTimePadDecrypt($key, $onetimepad);
  92. }
  93. /**
  94. * Saves or updates user password information
  95. *
  96. * This function is used to update the password information that
  97. * SquirrelMail stores in the existing PHP session. It does NOT
  98. * modify the password stored in the authentication system used
  99. * by the IMAP server.
  100. *
  101. * This function must be called before any html output is started.
  102. * Direct access to password information is deprecated. The saved
  103. * password information is available only to the SquirrelMail script
  104. * that is called/executed AFTER the current one. If your script
  105. * needs access to the saved password after a sqauth_save_password()
  106. * call, use the returned OTP encrypted key.
  107. *
  108. * @param string $pass password
  109. *
  110. * @return string Password encrypted with OTP. In case the script
  111. * wants to access the password information before
  112. * the end of its execution.
  113. *
  114. * @since 1.5.1
  115. *
  116. */
  117. function sqauth_save_password($pass) {
  118. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  119. $onetimepad = OneTimePadCreate(strlen($pass));
  120. sqsession_register($onetimepad,'onetimepad');
  121. $key = OneTimePadEncrypt($pass, $onetimepad);
  122. sqsetcookie('key', $key, false, $base_uri);
  123. return $key;
  124. }
  125. /**
  126. * Determine if an algorithm is supported by hash() and hash_hmac()
  127. *
  128. * @param string $algo Algorithm to find.
  129. *
  130. * @return string Functional $algo as used by hash() and hash_hmac()
  131. * or boolean FALSE
  132. *
  133. * @since 1.5.2
  134. */
  135. function scram_supports($algo) {
  136. $HASHs = hash_algos();
  137. if (check_php_version(7,2)) {
  138. $HMACs = hash_hmac_algos();
  139. $HASHs = array_values(array_intersect($HASHs, $HMACs));
  140. }
  141. $fAlgo = strtolower($algo);
  142. if (in_array($fAlgo, $HASHs))
  143. return $fAlgo;
  144. $fAlgo = str_replace('-', '', $fAlgo);
  145. if (in_array($fAlgo, $HASHs))
  146. return $fAlgo;
  147. return false;
  148. }
  149. /**
  150. * Build client nonce for SCRAM (See RFC 5802 for details)
  151. *
  152. * @return string A set of twenty random printable ASCII characters
  153. *
  154. * @since 1.5.2
  155. */
  156. function scram_nonce () {
  157. // All printable ASCII characters except commas are OK
  158. // (For simplicity, we're just going to use letters and numbers, though)
  159. $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  160. $max = strlen($chars) - 1;
  161. $nonce = '';
  162. for($i = 0; $i < 20; $i++) {
  163. $rndChr = random_int(0, $max);
  164. $nonce.= $chars[$rndChr];
  165. }
  166. return $nonce;
  167. }
  168. /**
  169. * Build client request for SCRAM (See RFC 5802 for details)
  170. *
  171. * @param string $username User ID
  172. * @param string $cbf Channel Binding Flag ('n', 'y', or 'p=tls-unique'/'p=tls-server-end-point')
  173. * @param string $nonce Client's random nonce data
  174. *
  175. * @return string The response to be sent to the server (base64 encoded)
  176. *
  177. * @since 1.5.2
  178. */
  179. function scram_request ($username,$cbf,$nonce) {
  180. return base64_encode($cbf.',,n='.$username.',r='.$nonce);
  181. }
  182. /**
  183. * Parse SCRAM challenge.
  184. * This function parses the challenge sent during SCRAM authentication and
  185. * returns an array. See the RFC for details on what's in the challenge string.
  186. *
  187. * @param string $challenge SCRAM Challenge
  188. * @param string $nonce Client's random nonce data
  189. *
  190. * @return array SCRAM challenge decoded data
  191. * or boolean FALSE
  192. *
  193. * @since 1.5.2
  194. */
  195. function scram_parse_challenge ($challenge,$nonce) {
  196. $chall = base64_decode($challenge, true);
  197. if ($chall === false) {
  198. // The challenge must be base64 encoded
  199. return false;
  200. }
  201. // Chall should now be r=NONCE,s=SALT,i=ITER
  202. $sReq = explode(',', $chall);
  203. $serNonce = '';
  204. $serSalt = '';
  205. $serIter = 0;
  206. for($i = 0; $i < count($sReq); $i++) {
  207. switch(substr($sReq[$i], 0, 2)) {
  208. case 'r=':
  209. $serNonce = substr($sReq[$i], 2);
  210. break;
  211. case 's=':
  212. $serSalt = substr($sReq[$i], 2);
  213. break;
  214. case 'i=':
  215. $serIter = substr($sReq[$i], 2);
  216. break;
  217. }
  218. }
  219. if (strlen($serNonce) <= strlen($nonce)) {
  220. //the server 'r' value must be bigger than the client 'r' value
  221. return false;
  222. }
  223. if (substr($serNonce, 0, strlen($nonce)) !== $nonce) {
  224. // The server 'r' value must begin with the client 'r' value
  225. return false;
  226. }
  227. if (is_numeric($serIter)) {
  228. $serIter = intval($serIter);
  229. } else {
  230. // The iteration value must be a number
  231. return false;
  232. }
  233. $serSaltV = base64_decode($serSalt, true);
  234. if ($serSaltV === false) {
  235. // The salt must be base64-encoded
  236. return false;
  237. }
  238. $parsed = array();
  239. $parsed['r'] = $serNonce;
  240. $parsed['s'] = $serSaltV;
  241. $parsed['i'] = $serIter;
  242. return $parsed;
  243. }
  244. /**
  245. * Build SCRAM response to challenge.
  246. * This function hashes the heck out of the password and all previous communications
  247. * to create a proof value which is then sent to the server as authentication.
  248. *
  249. * @param string $alg Hash algorithm to use ('sha1' or 'sha256')
  250. * @param string $username User ID
  251. * @param string $cbf Channel Binding Flag ('n', 'y', or 'p=tls-unique'/'p=tls-server-end-point')
  252. * @param string $cli_nonce Client's random nonce data
  253. * @param string $ser_nonce Client + Server's random nonce data
  254. * @param string $password User password supplied by User
  255. * @param string $salt Raw binary salt data, supplied by the server challenge
  256. * @param string $iter PBKDF2 iterations, supplied by the server challenge
  257. *
  258. * @return string The response to be sent to the server (base64 encoded)
  259. *
  260. * @since 1.5.2
  261. */
  262. function scram_response ($alg,$username,$cbf,$cli_nonce,$ser_nonce,$password,$salt,$iter) {
  263. // salt and hash password
  264. $salted_pass = hash_pbkdf2($alg, $password, $salt, $iter, 0, true);
  265. $cli_hash = hash_hmac($alg, 'Client Key', $salted_pass, true);
  266. $cli_key = hash($alg, $cli_hash, true);
  267. $c = base64_encode($cbf.',,');
  268. //generate unproofed communications
  269. $cli_request = 'n='.$username.',r='.$cli_nonce;
  270. $ser_challenge = 'r='.$ser_nonce.',s='.base64_encode($salt).',i='.$iter;
  271. $cli_response_unp = 'c='.$c.',r='.$ser_nonce;
  272. $comm_unp = $cli_request.','.$ser_challenge.','.$cli_response_unp;
  273. //hash unproofed communications
  274. $cli_sig = hash_hmac($alg, $comm_unp, $cli_key, true);
  275. $cli_proof = $cli_hash ^ $cli_sig;
  276. //generate proofed response
  277. $cli_response = $cli_response_unp.',p='.base64_encode($cli_proof);
  278. return base64_encode($cli_response);
  279. }
  280. /**
  281. * Verify SCRAM server response.
  282. * The final step in SCRAM is to make sure the server isn't just faking validation.
  283. * This is done by hashing the unproofed communications with a 'Server Key'
  284. * version of the hashed password, and comparing it with the server's final SCRAM message.
  285. *
  286. * @param string $alg Hash algorithm to use ('sha1' or 'sha256')
  287. * @param string $username User ID
  288. * @param string $cbf Channel Binding Flag ('n', 'y', or 'p=tls-unique'/'p=tls-server-end-point')
  289. * @param string $cli_nonce Client's random nonce data
  290. * @param string $ser_nonce Client + Server's random nonce data
  291. * @param string $password User password supplied by User
  292. * @param string $salt Raw binary salt data, supplied by the server challenge
  293. * @param string $iter PBKDF2 iterations, supplied by the server challenge
  294. * @param string $proof The server's final SCRAM message (base64 encoded)
  295. *
  296. * @return boolean Success or failure
  297. *
  298. * @since 1.5.2
  299. */
  300. function scram_verify ($alg,$username,$cbf,$cli_nonce,$ser_nonce,$password,$salt,$iter,$proof) {
  301. $proof = base64_decode($proof, true);
  302. if ($proof === false) {
  303. // The proof must be base64 encoded
  304. return false;
  305. }
  306. if (substr($proof, 0, 2) !== 'v=') {
  307. // The proof was not provided correctly
  308. return false;
  309. }
  310. $proof = substr($proof, 2);
  311. $proof = base64_decode($proof, true);
  312. if ($proof === false) {
  313. // The proof v value must be base64 encoded
  314. return false;
  315. }
  316. // salt and hash password
  317. $salted_pass = hash_pbkdf2($alg, $password, $salt, $iter, 0, true);
  318. $cli_hash = hash_hmac($alg, 'Client Key', $salted_pass, true);
  319. $cli_key = hash($alg, $cli_hash, true);
  320. $c = base64_encode($cbf.',,');
  321. //generate unproofed communications
  322. $cli_request = 'n='.$username.',r='.$cli_nonce;
  323. $ser_challenge = 'r='.$ser_nonce.',s='.base64_encode($salt).',i='.$iter;
  324. $cli_response_unp = 'c='.$c.',r='.$ser_nonce;
  325. $comm_unp = $cli_request.','.$ser_challenge.','.$cli_response_unp;
  326. //hash for server
  327. $ser_hash = hash_hmac($alg, 'Server Key', $salted_pass, true);
  328. $ser_proof = hash_hmac($alg, $comm_unp, $ser_hash, true);
  329. return $ser_proof === $proof;
  330. }
  331. /**
  332. * Given the challenge from the server, supply the response using cram-md5 (See
  333. * RFC 2195 for details)
  334. *
  335. * @param string $username User ID
  336. * @param string $password User password supplied by User
  337. * @param string $challenge The challenge supplied by the server
  338. * @return string The response to be sent to the IMAP server
  339. * @since 1.4.0
  340. */
  341. function cram_md5_response ($username,$password,$challenge) {
  342. $challenge=base64_decode($challenge);
  343. $hash=bin2hex(hmac_md5($challenge,$password));
  344. $response=base64_encode($username . " " . $hash) . "\r\n";
  345. return $response;
  346. }
  347. /**
  348. * Return Digest-MD5 response.
  349. * Given the challenge from the server, calculate and return the
  350. * response-string for digest-md5 authentication. (See RFC 2831 for more
  351. * details)
  352. *
  353. * @param string $username User ID
  354. * @param string $password User password supplied by User
  355. * @param string $challenge The challenge supplied by the server
  356. * @param string $service The service name, usually 'imap'; it is used to
  357. * define the digest-uri.
  358. * @param string $host The host name, usually the server's FQDN; it is used to
  359. * define the digest-uri.
  360. * @param string $authz Authorization ID (since 1.5.2)
  361. * @return string The response to be sent to the IMAP server
  362. * @since 1.4.0
  363. */
  364. function digest_md5_response ($username,$password,$challenge,$service,$host,$authz='') {
  365. $result=digest_md5_parse_challenge($challenge);
  366. //FIXME we should check that $result contains the expected values that we use below
  367. // verify server supports qop=auth
  368. // $qop = explode(",",$result['qop']);
  369. //if (!in_array("auth",$qop)) {
  370. // rfc2831: client MUST fail if no qop methods supported
  371. // return false;
  372. //}
  373. $cnonce = base64_encode(bin2hex(hmac_md5(microtime())));
  374. $ncount = "00000001";
  375. /* This can be auth (authentication only), auth-int (integrity protection), or
  376. auth-conf (confidentiality protection). Right now only auth is supported.
  377. DO NOT CHANGE THIS VALUE */
  378. $qop_value = "auth";
  379. $digest_uri_value = $service . '/' . $host;
  380. // build the $response_value
  381. //FIXME This will probably break badly if a server sends more than one realm
  382. $string_a1 = utf8_encode($username).":";
  383. $string_a1 .= utf8_encode($result['realm']).":";
  384. $string_a1 .= utf8_encode($password);
  385. $string_a1 = hmac_md5($string_a1);
  386. $A1 = $string_a1 . ":" . $result['nonce'] . ":" . $cnonce;
  387. if(!empty($authz)) {
  388. $A1 .= ":" . utf8_encode($authz);
  389. }
  390. $A1 = bin2hex(hmac_md5($A1));
  391. $A2 = "AUTHENTICATE:$digest_uri_value";
  392. // If qop is auth-int or auth-conf, A2 gets a little extra
  393. if ($qop_value != 'auth') {
  394. $A2 .= ':00000000000000000000000000000000';
  395. }
  396. $A2 = bin2hex(hmac_md5($A2));
  397. $string_response = $result['nonce'] . ':' . $ncount . ':' . $cnonce . ':' . $qop_value;
  398. $response_value = bin2hex(hmac_md5($A1.":".$string_response.":".$A2));
  399. $reply = 'charset=utf-8,username="' . $username . '",realm="' . $result["realm"] . '",';
  400. $reply .= 'nonce="' . $result['nonce'] . '",nc=' . $ncount . ',cnonce="' . $cnonce . '",';
  401. $reply .= "digest-uri=\"$digest_uri_value\",response=$response_value";
  402. $reply .= ',qop=' . $qop_value;
  403. if(!empty($authz)) {
  404. $reply .= ',authzid=' . $authz;
  405. }
  406. $reply = base64_encode($reply);
  407. return $reply . "\r\n";
  408. }
  409. /**
  410. * Parse Digest-MD5 challenge.
  411. * This function parses the challenge sent during DIGEST-MD5 authentication and
  412. * returns an array. See the RFC for details on what's in the challenge string.
  413. *
  414. * @param string $challenge Digest-MD5 Challenge
  415. * @return array Digest-MD5 challenge decoded data
  416. * @since 1.4.0
  417. */
  418. function digest_md5_parse_challenge($challenge) {
  419. $challenge=base64_decode($challenge);
  420. $parsed = array();
  421. while (!empty($challenge)) {
  422. if ($challenge[0] == ',') { // First char is a comma, must not be 1st time through loop
  423. $challenge=substr($challenge,1);
  424. }
  425. $key=explode('=',$challenge,2);
  426. $challenge=$key[1];
  427. $key=$key[0];
  428. if ($challenge[0] == '"') {
  429. // We're in a quoted value
  430. // Drop the first quote, since we don't care about it
  431. $challenge=substr($challenge,1);
  432. // Now explode() to the next quote, which is the end of our value
  433. $val=explode('"',$challenge,2);
  434. $challenge=$val[1]; // The rest of the challenge, work on it in next iteration of loop
  435. $value=explode(',',$val[0]);
  436. // Now, for those quoted values that are only 1 piece..
  437. if (sizeof($value) == 1) {
  438. $value=$value[0]; // Convert to non-array
  439. }
  440. } else {
  441. // We're in a "simple" value - explode to next comma
  442. $val=explode(',',$challenge,2);
  443. if (isset($val[1])) {
  444. $challenge=$val[1];
  445. } else {
  446. unset($challenge);
  447. }
  448. $value=$val[0];
  449. }
  450. $parsed["$key"]=$value;
  451. } // End of while loop
  452. return $parsed;
  453. }
  454. /**
  455. * Creates a HMAC digest that can be used for authentication purposes
  456. * See RFCs 2104, 2617, 2831
  457. *
  458. * Uses PHP's Hash extension if available (enabled by default in PHP
  459. * 5.1.2+ - see http://www.php.net/manual/en/hash.requirements.php
  460. * or, if installed on earlier PHP versions, the PECL hash module -
  461. * see http://pecl.php.net/package/hash
  462. *
  463. * Otherwise, will attempt to use the Mhash extension - see
  464. * http://www.php.net/manual/en/mhash.requirements.php
  465. *
  466. * Finally, a fall-back custom implementation is used if none of
  467. * the above are available.
  468. *
  469. * @param string $data The data to be encoded/hashed
  470. * @param string $key The (shared) secret key that will be used
  471. * to build the keyed hash. This argument is
  472. * technically optional, but only for internal
  473. * use (when the custom hash implementation is
  474. * being used) - external callers should always
  475. * specify a value for this argument.
  476. *
  477. * @return string The HMAC-MD5 digest string
  478. * @since 1.4.0
  479. *
  480. */
  481. function hmac_md5($data, $key='') {
  482. // use PHP's native Hash extension if possible
  483. //
  484. if (function_exists('hash_hmac'))
  485. return pack('H*', hash_hmac('md5', $data, $key));
  486. // otherwise, use (obsolete) mhash extension if available
  487. //
  488. if (extension_loaded('mhash')) {
  489. if ($key == '')
  490. $mhash = mhash(MHASH_MD5, $data);
  491. else
  492. $mhash = mhash(MHASH_MD5, $data, $key);
  493. return $mhash;
  494. }
  495. // or, our own implementation...
  496. //
  497. if (!$key)
  498. return pack('H*', md5($data));
  499. $key = str_pad($key, 64, chr(0x00));
  500. if (strlen($key) > 64)
  501. $key = pack("H*", md5($key));
  502. $k_ipad = $key ^ str_repeat(chr(0x36), 64);
  503. $k_opad = $key ^ str_repeat(chr(0x5c), 64);
  504. $hmac = hmac_md5($k_opad . pack('H*', md5($k_ipad . $data)));
  505. return $hmac;
  506. }
  507. /**
  508. * Fillin user and password based on SMTP auth settings.
  509. *
  510. * @param string $user Reference to SMTP username
  511. * @param string $pass Reference to SMTP password (unencrypted)
  512. * @since 1.4.11
  513. */
  514. function get_smtp_user(&$user, &$pass) {
  515. global $username, $smtp_auth_mech,
  516. $smtp_sitewide_user, $smtp_sitewide_pass;
  517. if ($smtp_auth_mech == 'none') {
  518. $user = '';
  519. $pass = '';
  520. } elseif ( isset($smtp_sitewide_user) && isset($smtp_sitewide_pass) &&
  521. !empty($smtp_sitewide_user)) {
  522. $user = $smtp_sitewide_user;
  523. $pass = $smtp_sitewide_pass;
  524. } else {
  525. $user = $username;
  526. $pass = sqauth_read_password();
  527. }
  528. // plugin authors note: override $user or $pass by
  529. // directly changing the arguments array contents
  530. // in your plugin e.g., $args[0] = 'new_username';
  531. //
  532. // NOTE: there is another hook in class/deliver/Deliver_SMTP.class.php
  533. // called "smtp_authenticate" that allows a plugin to run its own
  534. // custom authentication routine - this hook here is thus slightly
  535. // mis-named but is too old to change. Be careful that you do not
  536. // confuse your hook names.
  537. //
  538. $temp = array(&$user, &$pass);
  539. do_hook('smtp_auth', $temp);
  540. }