PageRenderTime 35ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/squirrelmail/functions/auth.php

#
PHP | 374 lines | 151 code | 40 blank | 183 comment | 40 complexity | 5f9e797bdc0abfc70e1268d061775d4f MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  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-2012 The SquirrelMail Project Team
  12. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  13. * @version $Id: auth.php 14249 2012-01-02 02:09:17Z pdontthink $
  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. * Given the challenge from the server, supply the response using cram-md5 (See
  127. * RFC 2195 for details)
  128. *
  129. * @param string $username User ID
  130. * @param string $password User password supplied by User
  131. * @param string $challenge The challenge supplied by the server
  132. * @return string The response to be sent to the IMAP server
  133. * @since 1.4.0
  134. */
  135. function cram_md5_response ($username,$password,$challenge) {
  136. $challenge=base64_decode($challenge);
  137. $hash=bin2hex(hmac_md5($challenge,$password));
  138. $response=base64_encode($username . " " . $hash) . "\r\n";
  139. return $response;
  140. }
  141. /**
  142. * Return Digest-MD5 response.
  143. * Given the challenge from the server, calculate and return the
  144. * response-string for digest-md5 authentication. (See RFC 2831 for more
  145. * details)
  146. *
  147. * @param string $username User ID
  148. * @param string $password User password supplied by User
  149. * @param string $challenge The challenge supplied by the server
  150. * @param string $service The service name, usually 'imap'; it is used to
  151. * define the digest-uri.
  152. * @param string $host The host name, usually the server's FQDN; it is used to
  153. * define the digest-uri.
  154. * @param string $authz Authorization ID (since 1.5.2)
  155. * @return string The response to be sent to the IMAP server
  156. * @since 1.4.0
  157. */
  158. function digest_md5_response ($username,$password,$challenge,$service,$host,$authz='') {
  159. $result=digest_md5_parse_challenge($challenge);
  160. //FIXME we should check that $result contains the expected values that we use below
  161. // verify server supports qop=auth
  162. // $qop = explode(",",$result['qop']);
  163. //if (!in_array("auth",$qop)) {
  164. // rfc2831: client MUST fail if no qop methods supported
  165. // return false;
  166. //}
  167. $cnonce = base64_encode(bin2hex(hmac_md5(microtime())));
  168. $ncount = "00000001";
  169. /* This can be auth (authentication only), auth-int (integrity protection), or
  170. auth-conf (confidentiality protection). Right now only auth is supported.
  171. DO NOT CHANGE THIS VALUE */
  172. $qop_value = "auth";
  173. $digest_uri_value = $service . '/' . $host;
  174. // build the $response_value
  175. //FIXME This will probably break badly if a server sends more than one realm
  176. $string_a1 = utf8_encode($username).":";
  177. $string_a1 .= utf8_encode($result['realm']).":";
  178. $string_a1 .= utf8_encode($password);
  179. $string_a1 = hmac_md5($string_a1);
  180. $A1 = $string_a1 . ":" . $result['nonce'] . ":" . $cnonce;
  181. if(!empty($authz)) {
  182. $A1 .= ":" . utf8_encode($authz);
  183. }
  184. $A1 = bin2hex(hmac_md5($A1));
  185. $A2 = "AUTHENTICATE:$digest_uri_value";
  186. // If qop is auth-int or auth-conf, A2 gets a little extra
  187. if ($qop_value != 'auth') {
  188. $A2 .= ':00000000000000000000000000000000';
  189. }
  190. $A2 = bin2hex(hmac_md5($A2));
  191. $string_response = $result['nonce'] . ':' . $ncount . ':' . $cnonce . ':' . $qop_value;
  192. $response_value = bin2hex(hmac_md5($A1.":".$string_response.":".$A2));
  193. $reply = 'charset=utf-8,username="' . $username . '",realm="' . $result["realm"] . '",';
  194. $reply .= 'nonce="' . $result['nonce'] . '",nc=' . $ncount . ',cnonce="' . $cnonce . '",';
  195. $reply .= "digest-uri=\"$digest_uri_value\",response=$response_value";
  196. $reply .= ',qop=' . $qop_value;
  197. if(!empty($authz)) {
  198. $reply .= ',authzid=' . $authz;
  199. }
  200. $reply = base64_encode($reply);
  201. return $reply . "\r\n";
  202. }
  203. /**
  204. * Parse Digest-MD5 challenge.
  205. * This function parses the challenge sent during DIGEST-MD5 authentication and
  206. * returns an array. See the RFC for details on what's in the challenge string.
  207. *
  208. * @param string $challenge Digest-MD5 Challenge
  209. * @return array Digest-MD5 challenge decoded data
  210. * @since 1.4.0
  211. */
  212. function digest_md5_parse_challenge($challenge) {
  213. $challenge=base64_decode($challenge);
  214. $parsed = array();
  215. while (!empty($challenge)) {
  216. if ($challenge{0} == ',') { // First char is a comma, must not be 1st time through loop
  217. $challenge=substr($challenge,1);
  218. }
  219. $key=explode('=',$challenge,2);
  220. $challenge=$key[1];
  221. $key=$key[0];
  222. if ($challenge{0} == '"') {
  223. // We're in a quoted value
  224. // Drop the first quote, since we don't care about it
  225. $challenge=substr($challenge,1);
  226. // Now explode() to the next quote, which is the end of our value
  227. $val=explode('"',$challenge,2);
  228. $challenge=$val[1]; // The rest of the challenge, work on it in next iteration of loop
  229. $value=explode(',',$val[0]);
  230. // Now, for those quoted values that are only 1 piece..
  231. if (sizeof($value) == 1) {
  232. $value=$value[0]; // Convert to non-array
  233. }
  234. } else {
  235. // We're in a "simple" value - explode to next comma
  236. $val=explode(',',$challenge,2);
  237. if (isset($val[1])) {
  238. $challenge=$val[1];
  239. } else {
  240. unset($challenge);
  241. }
  242. $value=$val[0];
  243. }
  244. $parsed["$key"]=$value;
  245. } // End of while loop
  246. return $parsed;
  247. }
  248. /**
  249. * Creates a HMAC digest that can be used for authentication purposes
  250. * See RFCs 2104, 2617, 2831
  251. *
  252. * Uses PHP's Hash extension if available (enabled by default in PHP
  253. * 5.1.2+ - see http://www.php.net/manual/en/hash.requirements.php
  254. * or, if installed on earlier PHP versions, the PECL hash module -
  255. * see http://pecl.php.net/package/hash
  256. *
  257. * Otherwise, will attempt to use the Mhash extension - see
  258. * http://www.php.net/manual/en/mhash.requirements.php
  259. *
  260. * Finally, a fall-back custom implementation is used if none of
  261. * the above are available.
  262. *
  263. * @param string $data The data to be encoded/hashed
  264. * @param string $key The (shared) secret key that will be used
  265. * to build the keyed hash. This argument is
  266. * technically optional, but only for internal
  267. * use (when the custom hash implementation is
  268. * being used) - external callers should always
  269. * specify a value for this argument.
  270. *
  271. * @return string The HMAC-MD5 digest string
  272. * @since 1.4.0
  273. *
  274. */
  275. function hmac_md5($data, $key='') {
  276. // use PHP's native Hash extension if possible
  277. //
  278. if (function_exists('hash_hmac'))
  279. return pack('H*', hash_hmac('md5', $data, $key));
  280. // otherwise, use (obsolete) mhash extension if available
  281. //
  282. if (extension_loaded('mhash')) {
  283. if ($key == '')
  284. $mhash = mhash(MHASH_MD5, $data);
  285. else
  286. $mhash = mhash(MHASH_MD5, $data, $key);
  287. return $mhash;
  288. }
  289. // or, our own implementation...
  290. //
  291. if (!$key)
  292. return pack('H*', md5($data));
  293. $key = str_pad($key, 64, chr(0x00));
  294. if (strlen($key) > 64)
  295. $key = pack("H*", md5($key));
  296. $k_ipad = $key ^ str_repeat(chr(0x36), 64);
  297. $k_opad = $key ^ str_repeat(chr(0x5c), 64);
  298. $hmac = hmac_md5($k_opad . pack('H*', md5($k_ipad . $data)));
  299. return $hmac;
  300. }
  301. /**
  302. * Fillin user and password based on SMTP auth settings.
  303. *
  304. * @param string $user Reference to SMTP username
  305. * @param string $pass Reference to SMTP password (unencrypted)
  306. * @since 1.4.11
  307. */
  308. function get_smtp_user(&$user, &$pass) {
  309. global $username, $smtp_auth_mech,
  310. $smtp_sitewide_user, $smtp_sitewide_pass;
  311. if ($smtp_auth_mech == 'none') {
  312. $user = '';
  313. $pass = '';
  314. } elseif ( isset($smtp_sitewide_user) && isset($smtp_sitewide_pass) &&
  315. !empty($smtp_sitewide_user)) {
  316. $user = $smtp_sitewide_user;
  317. $pass = $smtp_sitewide_pass;
  318. } else {
  319. $user = $username;
  320. $pass = sqauth_read_password();
  321. }
  322. // plugin authors note: override $user or $pass by
  323. // directly changing the arguments array contents
  324. // in your plugin e.g., $args[0] = 'new_username';
  325. //
  326. // NOTE: there is another hook in class/deliver/Deliver_SMTP.class.php
  327. // called "smtp_authenticate" that allows a plugin to run its own
  328. // custom authentication routine - this hook here is thus slightly
  329. // mis-named but is too old to change. Be careful that you do not
  330. // confuse your hook names.
  331. //
  332. $temp = array(&$user, &$pass);
  333. do_hook('smtp_auth', $temp);
  334. }