auth.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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-2010 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. sqgetGlobalVar('key', $key, SQ_COOKIE);
  88. sqgetGlobalVar('onetimepad', $onetimepad,SQ_SESSION);
  89. return OneTimePadDecrypt($key, $onetimepad);
  90. }
  91. /**
  92. * Saves or updates user password information
  93. *
  94. * This function is used to update the password information that
  95. * SquirrelMail stores in the existing PHP session. It does NOT
  96. * modify the password stored in the authentication system used
  97. * by the IMAP server.
  98. *
  99. * This function must be called before any html output is started.
  100. * Direct access to password information is deprecated. The saved
  101. * password information is available only to the SquirrelMail script
  102. * that is called/executed AFTER the current one. If your script
  103. * needs access to the saved password after a sqauth_save_password()
  104. * call, use the returned OTP encrypted key.
  105. *
  106. * @param string $pass password
  107. *
  108. * @return string Password encrypted with OTP. In case the script
  109. * wants to access the password information before
  110. * the end of its execution.
  111. *
  112. * @since 1.5.1
  113. *
  114. */
  115. function sqauth_save_password($pass) {
  116. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  117. $onetimepad = OneTimePadCreate(strlen($pass));
  118. sqsession_register($onetimepad,'onetimepad');
  119. $key = OneTimePadEncrypt($pass, $onetimepad);
  120. sqsetcookie('key', $key, false, $base_uri);
  121. return $key;
  122. }
  123. /**
  124. * Given the challenge from the server, supply the response using cram-md5 (See
  125. * RFC 2195 for details)
  126. *
  127. * @param string $username User ID
  128. * @param string $password User password supplied by User
  129. * @param string $challenge The challenge supplied by the server
  130. * @return string The response to be sent to the IMAP server
  131. * @since 1.4.0
  132. */
  133. function cram_md5_response ($username,$password,$challenge) {
  134. $challenge=base64_decode($challenge);
  135. $hash=bin2hex(hmac_md5($challenge,$password));
  136. $response=base64_encode($username . " " . $hash) . "\r\n";
  137. return $response;
  138. }
  139. /**
  140. * Return Digest-MD5 response.
  141. * Given the challenge from the server, calculate and return the
  142. * response-string for digest-md5 authentication. (See RFC 2831 for more
  143. * details)
  144. *
  145. * @param string $username User ID
  146. * @param string $password User password supplied by User
  147. * @param string $challenge The challenge supplied by the server
  148. * @param string $service The service name, usually 'imap'; it is used to
  149. * define the digest-uri.
  150. * @param string $host The host name, usually the server's FQDN; it is used to
  151. * define the digest-uri.
  152. * @param string $authz Authorization ID (since 1.5.2)
  153. * @return string The response to be sent to the IMAP server
  154. * @since 1.4.0
  155. */
  156. function digest_md5_response ($username,$password,$challenge,$service,$host,$authz='') {
  157. $result=digest_md5_parse_challenge($challenge);
  158. //FIXME we should check that $result contains the expected values that we use below
  159. // verify server supports qop=auth
  160. // $qop = explode(",",$result['qop']);
  161. //if (!in_array("auth",$qop)) {
  162. // rfc2831: client MUST fail if no qop methods supported
  163. // return false;
  164. //}
  165. $cnonce = base64_encode(bin2hex(hmac_md5(microtime())));
  166. $ncount = "00000001";
  167. /* This can be auth (authentication only), auth-int (integrity protection), or
  168. auth-conf (confidentiality protection). Right now only auth is supported.
  169. DO NOT CHANGE THIS VALUE */
  170. $qop_value = "auth";
  171. $digest_uri_value = $service . '/' . $host;
  172. // build the $response_value
  173. //FIXME This will probably break badly if a server sends more than one realm
  174. $string_a1 = utf8_encode($username).":";
  175. $string_a1 .= utf8_encode($result['realm']).":";
  176. $string_a1 .= utf8_encode($password);
  177. $string_a1 = hmac_md5($string_a1);
  178. $A1 = $string_a1 . ":" . $result['nonce'] . ":" . $cnonce;
  179. if(!empty($authz)) {
  180. $A1 .= ":" . utf8_encode($authz);
  181. }
  182. $A1 = bin2hex(hmac_md5($A1));
  183. $A2 = "AUTHENTICATE:$digest_uri_value";
  184. // If qop is auth-int or auth-conf, A2 gets a little extra
  185. if ($qop_value != 'auth') {
  186. $A2 .= ':00000000000000000000000000000000';
  187. }
  188. $A2 = bin2hex(hmac_md5($A2));
  189. $string_response = $result['nonce'] . ':' . $ncount . ':' . $cnonce . ':' . $qop_value;
  190. $response_value = bin2hex(hmac_md5($A1.":".$string_response.":".$A2));
  191. $reply = 'charset=utf-8,username="' . $username . '",realm="' . $result["realm"] . '",';
  192. $reply .= 'nonce="' . $result['nonce'] . '",nc=' . $ncount . ',cnonce="' . $cnonce . '",';
  193. $reply .= "digest-uri=\"$digest_uri_value\",response=$response_value";
  194. $reply .= ',qop=' . $qop_value;
  195. if(!empty($authz)) {
  196. $reply .= ',authzid=' . $authz;
  197. }
  198. $reply = base64_encode($reply);
  199. return $reply . "\r\n";
  200. }
  201. /**
  202. * Parse Digest-MD5 challenge.
  203. * This function parses the challenge sent during DIGEST-MD5 authentication and
  204. * returns an array. See the RFC for details on what's in the challenge string.
  205. *
  206. * @param string $challenge Digest-MD5 Challenge
  207. * @return array Digest-MD5 challenge decoded data
  208. * @since 1.4.0
  209. */
  210. function digest_md5_parse_challenge($challenge) {
  211. $challenge=base64_decode($challenge);
  212. $parsed = array();
  213. while (!empty($challenge)) {
  214. if ($challenge{0} == ',') { // First char is a comma, must not be 1st time through loop
  215. $challenge=substr($challenge,1);
  216. }
  217. $key=explode('=',$challenge,2);
  218. $challenge=$key[1];
  219. $key=$key[0];
  220. if ($challenge{0} == '"') {
  221. // We're in a quoted value
  222. // Drop the first quote, since we don't care about it
  223. $challenge=substr($challenge,1);
  224. // Now explode() to the next quote, which is the end of our value
  225. $val=explode('"',$challenge,2);
  226. $challenge=$val[1]; // The rest of the challenge, work on it in next iteration of loop
  227. $value=explode(',',$val[0]);
  228. // Now, for those quoted values that are only 1 piece..
  229. if (sizeof($value) == 1) {
  230. $value=$value[0]; // Convert to non-array
  231. }
  232. } else {
  233. // We're in a "simple" value - explode to next comma
  234. $val=explode(',',$challenge,2);
  235. if (isset($val[1])) {
  236. $challenge=$val[1];
  237. } else {
  238. unset($challenge);
  239. }
  240. $value=$val[0];
  241. }
  242. $parsed["$key"]=$value;
  243. } // End of while loop
  244. return $parsed;
  245. }
  246. /**
  247. * Creates a HMAC digest that can be used for auth purposes
  248. * See RFCs 2104, 2617, 2831
  249. * Uses mhash() extension if available
  250. *
  251. * @param string $data Data to apply hash function to.
  252. * @param string $key Optional key, which, if supplied, will be used to
  253. * calculate data's HMAC.
  254. * @return string HMAC Digest string
  255. * @since 1.4.0
  256. */
  257. function hmac_md5($data, $key='') {
  258. if (extension_loaded('mhash')) {
  259. if ($key== '') {
  260. $mhash=mhash(MHASH_MD5,$data);
  261. } else {
  262. $mhash=mhash(MHASH_MD5,$data,$key);
  263. }
  264. return $mhash;
  265. }
  266. if (!$key) {
  267. return pack('H*',md5($data));
  268. }
  269. $key = str_pad($key,64,chr(0x00));
  270. if (strlen($key) > 64) {
  271. $key = pack("H*",md5($key));
  272. }
  273. $k_ipad = $key ^ str_repeat(chr(0x36), 64) ;
  274. $k_opad = $key ^ str_repeat(chr(0x5c), 64) ;
  275. /* Heh, let's get recursive. */
  276. $hmac=hmac_md5($k_opad . pack("H*",md5($k_ipad . $data)) );
  277. return $hmac;
  278. }
  279. /**
  280. * Fillin user and password based on SMTP auth settings.
  281. *
  282. * @param string $user Reference to SMTP username
  283. * @param string $pass Reference to SMTP password (unencrypted)
  284. * @since 1.4.11
  285. */
  286. function get_smtp_user(&$user, &$pass) {
  287. global $username, $smtp_auth_mech,
  288. $smtp_sitewide_user, $smtp_sitewide_pass;
  289. if ($smtp_auth_mech == 'none') {
  290. $user = '';
  291. $pass = '';
  292. } elseif ( isset($smtp_sitewide_user) && isset($smtp_sitewide_pass) &&
  293. !empty($smtp_sitewide_user)) {
  294. $user = $smtp_sitewide_user;
  295. $pass = $smtp_sitewide_pass;
  296. } else {
  297. $user = $username;
  298. $pass = sqauth_read_password();
  299. }
  300. // plugin authors note: override $user or $pass by
  301. // directly changing the arguments array contents
  302. // in your plugin e.g., $args[0] = 'new_username';
  303. //
  304. $temp = array(&$user, &$pass);
  305. do_hook('smtp_auth', $temp);
  306. }