Handle subfolders as sent too!
[squirrelmail.git] / functions / auth.php
1 <?php
2
3 /**
4 * auth.php
5 *
6 * Contains functions used to do authentication.
7 *
8 * Dependencies:
9 * functions/global.php
10 * functions/strings.php.
11 *
12 * @copyright &copy; 1999-2007 The SquirrelMail Project Team
13 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 * @version $Id$
15 * @package squirrelmail
16 */
17
18
19 /**
20 * Detect whether user is logged in
21 *
22 * Function is similar to is_logged_in() function. If user is logged in, function
23 * returns true. If user is not logged in or session is expired, function saves $_POST
24 * and PAGE_NAME in session and returns false. POST information is saved in
25 * 'session_expired_post' variable, PAGE_NAME is saved in 'session_expired_location'.
26 *
27 * Script that uses this function instead of is_logged_in() function, must handle user
28 * level messages.
29 * @return boolean
30 * @since 1.5.1
31 */
32 function sqauth_is_logged_in() {
33 if ( sqsession_is_registered('user_is_logged_in') ) {
34 return true;
35 }
36
37 // First we store some information in the new session to prevent
38 // information-loss.
39 $session_expired_post = $_POST;
40 if (defined('PAGE_NAME'))
41 $session_expired_location = PAGE_NAME;
42 else
43 $session_expired_location = '';
44
45 if (!sqsession_is_registered('session_expired_post')) {
46 sqsession_register($session_expired_post,'session_expired_post');
47 }
48 if (!sqsession_is_registered('session_expired_location')) {
49 sqsession_register($session_expired_location,'session_expired_location');
50 }
51
52 session_write_close();
53
54 return false;
55 }
56
57 /**
58 * Reads and decodes stored user password information
59 *
60 * Direct access to password information is deprecated.
61 * @return string password in plain text
62 * @since 1.5.1
63 */
64 function sqauth_read_password() {
65 sqgetGlobalVar('key', $key, SQ_COOKIE);
66 sqgetGlobalVar('onetimepad', $onetimepad,SQ_SESSION);
67
68 return OneTimePadDecrypt($key, $onetimepad);
69 }
70
71 /**
72 * Saves or updates user password information
73 *
74 * This function is used to update the password information that
75 * SquirrelMail stores in the existing PHP session. It does NOT
76 * modify the password stored in the authentication system used
77 * by the IMAP server.
78 *
79 * This function must be called before any html output is started.
80 * Direct access to password information is deprecated. The saved
81 * password information is available only to the SquirrelMail script
82 * that is called/executed AFTER the current one. If your script
83 * needs access to the saved password after a sqauth_save_password()
84 * call, use the returned OTP encrypted key.
85 *
86 * @param string $pass password
87 *
88 * @return string Password encrypted with OTP. In case the script
89 * wants to access the password information before
90 * the end of its execution.
91 *
92 * @since 1.5.1
93 *
94 */
95 function sqauth_save_password($pass) {
96 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
97
98 $onetimepad = OneTimePadCreate(strlen($pass));
99 sqsession_register($onetimepad,'onetimepad');
100 $key = OneTimePadEncrypt($pass, $onetimepad);
101 sqsetcookie('key', $key, false, $base_uri);
102 return $key;
103 }
104
105 /**
106 * Given the challenge from the server, supply the response using cram-md5 (See
107 * RFC 2195 for details)
108 *
109 * @param string $username User ID
110 * @param string $password User password supplied by User
111 * @param string $challenge The challenge supplied by the server
112 * @return string The response to be sent to the IMAP server
113 * @since 1.4.0
114 */
115 function cram_md5_response ($username,$password,$challenge) {
116 $challenge=base64_decode($challenge);
117 $hash=bin2hex(hmac_md5($challenge,$password));
118 $response=base64_encode($username . " " . $hash) . "\r\n";
119 return $response;
120 }
121
122 /**
123 * Return Digest-MD5 response.
124 * Given the challenge from the server, calculate and return the
125 * response-string for digest-md5 authentication. (See RFC 2831 for more
126 * details)
127 *
128 * @param string $username User ID
129 * @param string $password User password supplied by User
130 * @param string $challenge The challenge supplied by the server
131 * @param string $service The service name, usually 'imap'; it is used to
132 * define the digest-uri.
133 * @param string $host The host name, usually the server's FQDN; it is used to
134 * define the digest-uri.
135 * @param string $authz Authorization ID (since 1.5.2)
136 * @return string The response to be sent to the IMAP server
137 * @since 1.4.0
138 */
139 function digest_md5_response ($username,$password,$challenge,$service,$host,$authz='') {
140 $result=digest_md5_parse_challenge($challenge);
141 //FIXME we should check that $result contains the expected values that we use below
142
143 // verify server supports qop=auth
144 // $qop = explode(",",$result['qop']);
145 //if (!in_array("auth",$qop)) {
146 // rfc2831: client MUST fail if no qop methods supported
147 // return false;
148 //}
149 $cnonce = base64_encode(bin2hex(hmac_md5(microtime())));
150 $ncount = "00000001";
151
152 /* This can be auth (authentication only), auth-int (integrity protection), or
153 auth-conf (confidentiality protection). Right now only auth is supported.
154 DO NOT CHANGE THIS VALUE */
155 $qop_value = "auth";
156
157 $digest_uri_value = $service . '/' . $host;
158
159 // build the $response_value
160 //FIXME This will probably break badly if a server sends more than one realm
161 $string_a1 = utf8_encode($username).":";
162 $string_a1 .= utf8_encode($result['realm']).":";
163 $string_a1 .= utf8_encode($password);
164 $string_a1 = hmac_md5($string_a1);
165 $A1 = $string_a1 . ":" . $result['nonce'] . ":" . $cnonce;
166 if(!empty($authz)) {
167 $A1 .= ":" . utf8_encode($authz);
168 }
169 $A1 = bin2hex(hmac_md5($A1));
170 $A2 = "AUTHENTICATE:$digest_uri_value";
171 // If qop is auth-int or auth-conf, A2 gets a little extra
172 if ($qop_value != 'auth') {
173 $A2 .= ':00000000000000000000000000000000';
174 }
175 $A2 = bin2hex(hmac_md5($A2));
176
177 $string_response = $result['nonce'] . ':' . $ncount . ':' . $cnonce . ':' . $qop_value;
178 $response_value = bin2hex(hmac_md5($A1.":".$string_response.":".$A2));
179
180 $reply = 'charset=utf-8,username="' . $username . '",realm="' . $result["realm"] . '",';
181 $reply .= 'nonce="' . $result['nonce'] . '",nc=' . $ncount . ',cnonce="' . $cnonce . '",';
182 $reply .= "digest-uri=\"$digest_uri_value\",response=$response_value";
183 $reply .= ',qop=' . $qop_value;
184 if(!empty($authz)) {
185 $reply .= ',authzid=' . $authz;
186 }
187 $reply = base64_encode($reply);
188 return $reply . "\r\n";
189
190 }
191
192 /**
193 * Parse Digest-MD5 challenge.
194 * This function parses the challenge sent during DIGEST-MD5 authentication and
195 * returns an array. See the RFC for details on what's in the challenge string.
196 *
197 * @param string $challenge Digest-MD5 Challenge
198 * @return array Digest-MD5 challenge decoded data
199 * @since 1.4.0
200 */
201 function digest_md5_parse_challenge($challenge) {
202 $challenge=base64_decode($challenge);
203 $parsed = array();
204 while (!empty($challenge)) {
205 if ($challenge{0} == ',') { // First char is a comma, must not be 1st time through loop
206 $challenge=substr($challenge,1);
207 }
208 $key=explode('=',$challenge,2);
209 $challenge=$key[1];
210 $key=$key[0];
211 if ($challenge{0} == '"') {
212 // We're in a quoted value
213 // Drop the first quote, since we don't care about it
214 $challenge=substr($challenge,1);
215 // Now explode() to the next quote, which is the end of our value
216 $val=explode('"',$challenge,2);
217 $challenge=$val[1]; // The rest of the challenge, work on it in next iteration of loop
218 $value=explode(',',$val[0]);
219 // Now, for those quoted values that are only 1 piece..
220 if (sizeof($value) == 1) {
221 $value=$value[0]; // Convert to non-array
222 }
223 } else {
224 // We're in a "simple" value - explode to next comma
225 $val=explode(',',$challenge,2);
226 if (isset($val[1])) {
227 $challenge=$val[1];
228 } else {
229 unset($challenge);
230 }
231 $value=$val[0];
232 }
233 $parsed["$key"]=$value;
234 } // End of while loop
235 return $parsed;
236 }
237
238 /**
239 * Creates a HMAC digest that can be used for auth purposes
240 * See RFCs 2104, 2617, 2831
241 * Uses mhash() extension if available
242 *
243 * @param string $data Data to apply hash function to.
244 * @param string $key Optional key, which, if supplied, will be used to
245 * calculate data's HMAC.
246 * @return string HMAC Digest string
247 * @since 1.4.0
248 */
249 function hmac_md5($data, $key='') {
250 if (extension_loaded('mhash')) {
251 if ($key== '') {
252 $mhash=mhash(MHASH_MD5,$data);
253 } else {
254 $mhash=mhash(MHASH_MD5,$data,$key);
255 }
256 return $mhash;
257 }
258 if (!$key) {
259 return pack('H*',md5($data));
260 }
261 $key = str_pad($key,64,chr(0x00));
262 if (strlen($key) > 64) {
263 $key = pack("H*",md5($key));
264 }
265 $k_ipad = $key ^ str_repeat(chr(0x36), 64) ;
266 $k_opad = $key ^ str_repeat(chr(0x5c), 64) ;
267 /* Heh, let's get recursive. */
268 $hmac=hmac_md5($k_opad . pack("H*",md5($k_ipad . $data)) );
269 return $hmac;
270 }
271
272 /**
273 * Fillin user and password based on SMTP auth settings.
274 *
275 * @param string $user Reference to SMTP username
276 * @param string $pass Reference to SMTP password (unencrypted)
277 * @since 1.4.11
278 */
279 function get_smtp_user(&$user, &$pass) {
280 global $username, $smtp_auth_mech,
281 $smtp_sitewide_user, $smtp_sitewide_pass;
282
283 if ($smtp_auth_mech == 'none') {
284 $user = '';
285 $pass = '';
286 } elseif ( isset($smtp_sitewide_user) && isset($smtp_sitewide_pass) &&
287 !empty($smtp_sitewide_user)) {
288 $user = $smtp_sitewide_user;
289 $pass = $smtp_sitewide_pass;
290 } else {
291 $user = $username;
292 $pass = sqauth_read_password();
293 }
294
295 // plugin authors note: override $user or $pass by
296 // directly changing the arguments array contents
297 // in your plugin e.g., $args[0] = 'new_username';
298 //
299 $temp = array(&$user, &$pass);
300 do_hook('smtp_auth', $temp);
301 }